我有两个非常简单的对象,一个对象应该在集合中以“一对多”关系包含另一个对象。对象被正确插入到数据库中,但“children”表中的外键始终为“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();
}
有人可以解释一下为什么会这样吗?