我有兩個非常簡單的對象,一個對象應包含在一組的「一個一對多」關係,另一個。對象在數據庫中正確插入,但「子」表中的外鍵始終爲「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();
}
有些人可以解釋爲什麼會發生這種情況嗎?
你可以發表你的答案? – Rajesh