简体   繁体   English

Hibernate-持久保存@OneToMany实体的集合

[英]Hibernate - persisting collection of @OneToMany entities

I wanted to map a simple parent-child relationship. 我想映射一个简单的父子关系。

@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 case: 测试用例:

@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 didn't assign mother's ID in child entity. Hibernate并未在子实体中分配母亲的ID。

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

When I assign child to mother directly, its working. 当我直接把孩子分配给母亲时,它的工作。

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

By setting 通过设置

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

You declared mappedBy=mother , that means that User is the owning entity of the relation and the relation is set on mother field. 您声明了mappedBy=mother ,这意味着User是该关系的拥有实体,并且该关系在mother字段中设置。 In JPA/Hibernate the owning side is used to persist and keep relations between entities. 在JPA / Hibernate中,拥有方用于保留并保持实体之间的关系。

Please take a look at that: https://stackoverflow.com/a/21068644/2392469 请看一下: https : //stackoverflow.com/a/21068644/2392469

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM