我有以下带注释的Hibernate实体类:
@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; } }
我的意图是Cat和Kitten之间的双向一对多/多对一关系,其中Kitten是“拥有者”.
我想要发生的是当我创造一只新猫,然后是一只引用猫的新小猫时,我猫上的小猫套装应该包含新的小猫.但是,在以下测试中不会发生这种情况:
@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); // <-- ASSERTION FAILS assertEquals(kitten,new ArrayList<Kitten>(cat.getKittens()).get(0)); }
即使在重新查询Cat之后,Set仍然是空的:
// added before tx.commit() and assertions cat = (Cat)session.get(Cat.class,cat.getId());
我对Hibernate的期望太高了吗?或者是我自己管理收藏品的负担? (Annotations) documentation没有任何迹象表明我需要在父对象上创建方便的addTo * / removeFrom *方法.
有人可以告诉我Hibernate对这种关系的期望是什么吗?或者,如果没有别的,请指出正确的Hibernate文档,告诉我在这里应该发生什么.
我需要做什么才能使父集合自动包含子实体?