简体   繁体   English

Hibernate JPA持久保存具有空父ID的子实体

[英]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.

相关问题 JPA / Hibernate OneToOne关联,持久调用插入具有空ID的实体 - JPA/Hibernate OneToOne association, persist call inserts entity with null Id JPA /休眠的entityManager.persist(..)使实体的集合变为空,即使它们已保存 - JPA/Hibernate entityManager.persist(..) makes the entity's collection to become null even though they are saved JPA / Hibernate - 在子更改时更新父实体 - JPA / Hibernate - Update parent entity on child changes 子实体中的JPA空父外键 - JPA Null parent foreign key in child entity JPA OneToOne 关系在保存父实体时不会保留子实体 - JPA OneToOne relation doesnt persist child entity when saving parent 如何在 Spring JPA/Hibernate 中使用 JoinTable 仅通过 ID 设置引用父实体的子实体 - How to set up a child entity referencing parent by only ID using a JoinTable in Spring JPA/Hibernate Hibernate:合并父级后子ID为空 - Hibernate: Child id is null after merging parent 父 id 未保存在子表 Spring JPA2 @OneToMany 关系中 - Parent id is not saved in child table Spring JPA2 @OneToMany relation 如何通过JPA / Hibernate在孩子的ID中引用父母的ID? - How to reference a parent's id in a child's id with JPA/Hibernate? Hibernate / JPA 在父实体或子实体中 @JoinColumn 的 position 差异 - Hibernate / JPA difference in position of @JoinColumn in parent or child entity
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM