I have the following annotated Hibernate entity classes:
@Entity public class Cat { @Column(name = "ID") @GeneratedValue(strategy = GenerationType.AUTO) @Id private Long id; @OneToMany(mappedBy = "cat", cascade = CascadeType.ALL, fetch = FetchType.EAGER) private Set<Kitten> kittens = new HashSet<Kitten>(); public void setId(Long id) { this.id = id; } public Long getId() { return id; } public void setKittens(Set<Kitten> kittens) { this.kittens = kittens; } public Set<Kitten> getKittens() { return kittens; } } @Entity public class Kitten { @Column(name = "ID") @GeneratedValue(strategy = GenerationType.AUTO) @Id private Long id; @ManyToOne(cascade = CascadeType.ALL, fetch = FetchType.EAGER) private Cat cat; public void setId(Long id) { this.id = id; } public Long getId() { return id; } public void setCat(Cat cat) { this.cat = cat; } public Cat getCat() { return cat; } }
My intention here is a one-to-many / many-one bi-directional relationship between "Cat" and "Kitten", and the kitten is the "owning side".
What I want to do is when I create a new Cat and then a new kitten referring to Cat. The kitten kit on my cat should contain a new kitten . However, this fails in the following test:
@Test public void testAssociations() { Session session = HibernateUtil.getSessionFactory().getCurrentSession(); Transaction tx = session.beginTransaction(); Cat cat = new Cat(); session.save(cat); Kitten kitten = new Kitten(); kitten.setCat(cat); session.save(kitten); tx.commit(); assertNotNull(kitten.getCat()); assertEquals(cat.getId(), kitten.getCat().getId()); assertTrue(cat.getKittens().size() == 1);
Even after retrying Cat, Set is still empty:
// added before tx.commit() and assertions cat = (Cat)session.get(Cat.class, cat.getId());
Am I expecting too much from Hibernate here? Or the burden for me to manage the collection myself? The documentation (annotations) does not indicate that I need to create convenient addTo* / removeFrom* methods for my parent object.
Can someone please enlighten me, what are my expectations from Hibernate with this relationship? Or, if nothing else, give me the correct Hibernate documentation that will tell me what I should expect here.
What do I need to do so that the parent collection automatically contains a child Entity?
java hibernate jpa hibernate-annotations many-to-one
Rob hruska
source share