Hi everybody
I have problems using parent/child model. I followed Bid-Item example from the book "Java Persistence with Hibernate". Can anybody help me out?
Here is the Bid class
Code:
@Entity
public class Bid implements Serializable {
@Id
@GeneratedValue
private Long bid_id;
private String name;
@ManyToOne ( targetEntity=Item.class, cascade = { CascadeType.ALL })
@JoinColumn(name="itemid", nullable=false)
private Item item;
public Item getItem() {
return item;
}
public void setItem(Item item) {
this.item = item;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
And Item class
Code:
@Entity
public class Item implements Serializable {
@Id
@GeneratedValue
private Long item_id;
private String name;
@OneToMany(mappedBy="item", cascade={CascadeType.PERSIST, CascadeType.MERGE})
private Set<Bid> bids = new HashSet<Bid>();
public Set<Bid> getBids() {
return bids;
}
public void setBids(Set<Bid> bids) {
this.bids = bids;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
They are copied from page 260-269.
My test program is listed below.
Code:
SessionFactory sFactory = config.buildSessionFactory();
Session s = sFactory.openSession();
s.beginTransaction();
Item item = new Item();
item.setName("item");
Bid bid1 = new Bid();
bid1.setName("bid1");
// In book, the following two lines is replaced by Item.addBid()
bid1.setItem(item);
item.getBids().add(bid1);
s.save(item);
s.flush();
s.getTransaction().commit();
s.close();
According to the book, bid1 should also be persisted. But in fact, I have only item record but no bid in database.
What's the problem here?
Thanks.