Reputation: 3050
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", "[email protected]");
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, [email protected], name=null, surname=null, userGroups=[], userLogin=abel]
When I assign child to mother directly, its working.
User user = new User("kain", "[email protected]");
User ewa = session.find(User.class, 1L);
user.setMother(ewa);
session.persist(user); //ok
Upvotes: 0
Views: 150
Reputation: 764
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
Upvotes: 1