[英]Hibernate JPA persist saved child entity with null parent id
I have two entities: parent : 我有两个实体:parent:
public class UserGroup{
@OneToMany(fetch = FetchType.EAGER, mappedBy = "userGroup", cascade = CascadeType.ALL)
private List<User> users;
}
and child: 和孩子:
public class User{
@ManyToOne(fetch = FetchType.EAGER)
@Fetch(FetchMode.SELECT)
@JoinColumn(name = "user_group_id")
private UserGroup userGroup;
}
when i am trying to save UserGroup with one User in list of users, with this method: 当我尝试使用以下方法在用户列表中使用一个用户保存UserGroup时:
@Transactional
public E save(E e) {
em.persist(e);
em.flush();
em.refresh(e);
return e;
}
my parent and child is getting saved, but user_group_id in child object is null. 我的父母和孩子正在保存,但子对象中的user_group_id为null。 Is there any solution?
有什么解决办法吗?
By considering you are giving UserGroup
object along with list of User
to save method: so your code should be: 考虑到您
UserGroup
对象以及User
列表以保存方法:因此您的代码应为:
em.save(userGroup);
for(User user : UserGroup.getUsers())
{
user.setuser_group_id(userGroup.getUserGroupId());
em.save(user);
}
You have a bidirectional relationship. 您有双向关系。 The correct way of saving it is putting both references in the entities.
保存它的正确方法是将两个引用都放在实体中。
You should do: 你应该做:
userGroup.getUsers().add(user);
user.setUserGroup(userGroup);
entityManager.persist(userGroup);
In your parent setter method of child, do this. 在您的孩子的父母二传手方法中,执行此操作。
public void setChildren(Collection<Child> children) {
this.children = children;
for(Child child: this.children) {
child.setParent(this)
}
}
This should solve. 这应该解决。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.