0

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.

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
Neil Stockton
  • 11,383
  • 3
  • 34
  • 29
Damian
  • 2,930
  • 6
  • 39
  • 61

1 Answers1

1

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. In JPA/Hibernate the owning side is used to persist and keep relations between entities.

Please take a look at that: https://stackoverflow.com/a/21068644/2392469

Community
  • 1
  • 1
gmaslowski
  • 774
  • 5
  • 13
  • Without mappedBy Hibernate will create separate table to save related users id.With mappedBy Hibernte won't track changes made to the mother's children set. So there is no way to make it work as expected, there is no way to tell Hibernate "use MOTHER_ID Filed to track changes instead of a separate table"? – Damian Jun 12 '16 at 12:09