Hibernate - 持久收集@OneToMany实体

时间:2016-06-12 02:41:06

标签: java hibernate

我想映射一个简单的父子关系。

@OneToMany(fetch = FetchType.EAGER, cascade = CascadeType.ALL, mappedBy = "mother")
public Set<User> getChildren() {
    return children;
}

@ManyToOne(fetch = FetchType.EAGER, cascade = CascadeType.ALL)
@JoinColumn(name = "MOTHER_ID")
public User getMother() {
    return this.mother;
}

测试用例:

@Test
public void t4adopt() {
    User ewa = session.find(User.class, 1L);
    User user = new User("abel", "abel@garden.com");
    session.persist(user);
    ewa.getChildren().add(user);
    System.out.println("save eva's children");
    session.saveOrUpdate(ewa);
    //session.save(user);
    session.flush();
    System.out.println("4. " + ewa);
    session.refresh(user);
    System.out.println("5. " + user);
}
@Before
public void start() {
    session.getTransaction().begin();
}

@After
public void close() {
    session.getTransaction().commit();
    session.close();
}

Hibernate没有在子实体中分配母亲的身份证。

5. User [idUser=3, mother=null, userEmail=abel@garden.com, name=null, surname=null, userGroups=[], userLogin=abel]

当我直接将孩子分配给母亲时,其工作。

User user = new User("kain", "kain@garden.com");
User ewa = session.find(User.class, 1L);
user.setMother(ewa);
session.persist(user); //ok

1 个答案:

答案 0 :(得分:1)

通过设置

@OneToMany(fetch = FetchType.EAGER, cascade = CascadeType.ALL,
mappedBy = "mother") public Set<User> getChildren() {
return children; }

您声明了mappedBy=mother,这意味着User是该关系的拥有实体,并且该关系在mother字段上设置。在JPA / Hibernate中,拥有方用于持久化并保持实体之间的关系。

请看一下:https://stackoverflow.com/a/21068644/2392469