Need help with Hibernate? Read this first:
http://www.hibernate.org/ForumMailingli ... AskForHelp
Hibernate version:Hibernate2.18
I have two entity (Item Bid), they are One to many relation.
Code:
<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate Mapping DTD 2.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-2.0.dtd" >
<hibernate-mapping package="hibernate.study.beans">
<class name="Item" table="item">
<id name="id" type="java.lang.Integer" column="ITEM_ID">
<generator class="native"/>
</id>
<timestamp name="created" column="CREATED" />
<property name="itemName" type="java.lang.String" column="ITEM_NAME" not-null="true" length="45"/>
<set name="bids" inverse="true" lazy="true" cascade="all-delete-orphan">
<key column="ITEM_ID"/>
<one-to-many class="Bid"/>
</set>
</class>
</hibernate-mapping>
Code:
<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate Mapping DTD 2.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-2.0.dtd" >
<hibernate-mapping package="hibernate.study.beans">
<class name="Bid" table="bid">
<id name="id" type="java.lang.Integer" column="BID_ID">
<generator class="native"/>
</id>
<property name="bidName" type="java.lang.String" column="BID_NAME" not-null="true" length="45"/>
<many-to-one name="item" class="Item" column="ITEM_ID" not-null="true"/>
</class>
</hibernate-mapping>
I use the hbm2class to create the java class.
Now I want to insert a list of bid to the Item which is loaded from the database.
Code:
Session session = HibernateUtil.getSession();
HibernateUtil.beginTransaction();
Item i = (Item) session.load(Item.class,new Integer(7));
Bid b = new Bid();
b.setBidName("bid");
Bid b1 = new Bid();
b.setBidName("bid1");
Bid b2 = new Bid();
b.setBidName("bid2");
Bid b3 = new Bid();
b.setBidName("bid3");
b.setItem(i);
b1.setItem(i);
b2.setItem(i);
b3.setItem(i);
Collection<Bid> bids = new HashSet<Bid>();
bids.add(b);
bids.add(b1);
bids.add(b2);
bids.add(b3);
i.getBids().addAll(bids);
session.saveOrUpdate(i);
HibernateUtil.commitTransaction();
HibernateUtil.closeSession();
but only the b3 bid can be inserted into database.
must I insert those bids one to one?
the following is the hibernate printed sql.
Hibernate: select item0_.ITEM_ID as ITEM_ID0_, item0_.CREATED as CREATED0_, item0_.ITEM_NAME as ITEM_NAME0_ from item item0_ where item0_.ITEM_ID=?
Hibernate: select bids0_.ITEM_ID as ITEM_ID__, bids0_.BID_ID as BID_ID__, bids0_.BID_ID as BID_ID0_, bids0_.BID_NAME as BID_NAME0_, bids0_.ITEM_ID as ITEM_ID0_ from bid bids0_ where bids0_.ITEM_ID=?
Hibernate: insert into bid (BID_NAME, ITEM_ID) values (?, ?)
Hibernate: update item set CREATED=?, ITEM_NAME=? where ITEM_ID=? and CREATED=?