我有两个非常简单的对象,并且一个对象应在一组“一对多”关系中包含另一个对象。对象已正确插入数据库中,但“子项”表中的外键始终为“ null”。
我不知道为什么:
这是测试对象,它将子对象固定在其集合中:
@Entity @Table(name="test") public class TestObj { public TestObj(){} private Long id; @Id @GeneratedValue(strategy=GenerationType.IDENTITY) public Long getId() { return id; } public void setId(Long id) { this.id = id; } private Set<Children> children = new HashSet<Children>(); @OneToMany(mappedBy = "testObj", cascade = CascadeType.ALL) public synchronized Set<Children> getChildren() { return children; } public synchronized void setChildren(Set<Children> children) { this.children = children; } public void addChildren(Children child){ children.add(child); } }
这是子对象,它包含指向“ TestObj”的反向链接:
@Entity @Table(name = "children") public class Children { public Children(){} private Long id; @Id @GeneratedValue(strategy=GenerationType.IDENTITY) public Long getId() { return id; } public void setId(Long id) { this.id = id; } private TestObj testObj; @ManyToOne @JoinColumn public TestObj getTestObj() { return testObj; } public void setTestObj(TestObj testObj) { this.testObj = testObj; } }
我用下面的代码坚持这个对象:
EntityManagerFactory entityManagerFactory = HibernateEntityMangerSingelton.getEntityManagerFactory(); EntityManager entityManager = entityManagerFactory.createEntityManager(); entityManager.getTransaction().begin(); TestObj user = new TestObj(); Children child = new Children(); user.addChildren(child); try { entityManager.persist(user); entityManager.getTransaction().commit(); } catch (Exception e) { System.out.println(e); }finally{ entityManager.close(); }
有人可以解释一下为什么会这样吗?
这很简单:您永远不会初始化中的testObj字段Children(应将其命名为Child,BTW)。Children.testObj是关联的所有者,并且是映射到连接列的字段,因此,如果为空,则连接列将为空。
testObj
Children
Children.testObj