Hibernate @OneToMany remove child from list when updating parent

前端 未结 1 947
深忆病人
深忆病人 2020-12-12 19:39

I have the following entities:

TEAM

@Entity
@Table
public class Team {
[..]
private Set userTeamRoles;

/**
 * @return the userTe         


        
相关标签:
1条回答
  • 2020-12-12 19:55
    1. Instead of replacing the collection (team.setUserTeamRoles(new HashSet<UserTeamRole>());) you have to clear() the existing one. This happens because if Hibernate loads the entity (and its collections) from DB, it "manages" them, ie. tracks their changes. Generally when using Hibernate it's better not to create any setters for collections (lists, sets). Create only the getter, and clear the collection returned by it, ie:

      team.getUserTeamRoles().clear();

    2. Another thing is that you miss orphan deletion (ie. delete child object when it's removed from collection in the parent). To enable it, you need to add @OneToMany(orphanRemoval=true) in owning entity.

    0 讨论(0)
提交回复
热议问题