java.lang.IllegalStateException:同一实体的多个表示形式,@ManyToMany 3个实体

2022-08-31 14:41:05

我有3个实体,具有ManyToMany关系:

角色实体:

@Entity
public class Role {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Integer roleID;
    private String roleName;
    private String description;

    @ManyToMany(cascade = {CascadeType.MERGE, CascadeType.PERSIST, CascadeType.REFRESH}, fetch = FetchType.EAGER)
    @JoinTable(name = "role_permission", joinColumns = {@JoinColumn(name = "role_id")}, inverseJoinColumns = {@JoinColumn(name = "permission_id")})
    private Set<Permission> permissions = new LinkedHashSet<Permission>();
}

权限实体:

@Entity
public class Permission {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private int permissionID;
    private String permissionName;
    private String description;

    @ManyToMany(cascade = {CascadeType.MERGE, CascadeType.PERSIST, CascadeType.REFRESH}, fetch = FetchType.EAGER)
    @JoinTable(name = "permission_functionality", joinColumns = {@JoinColumn(name = "permission_id")}, inverseJoinColumns = {@JoinColumn(name = "functionality_id")})
    private Set<Functionality> functionalities = new LinkedHashSet<>();
}

功能实体:

@Entity
public class Functionality {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Integer id;
    private String name;
}

我做了以下操作:

  1. 我创建了3个功能:

    Functionality1, Functionality2, Functionality3
    
  2. 然后创建了 2 个权限:

    Permission1 with Functionality1, Functionality2
    
    Permission2 with Functionality2, Functionality3
    
  3. 然后创建了一个角色:

    Role1 with Permission1 and Permission2 
    

我遇到以下异常:

java.lang.IllegalStateException:同一实体的多个表示形式 [com.persistence.entity.admin.Functionality#1] 正在合并。分离: [com.persistence.entity.admin.Functionality@4729256a];分离式: [com.persistence.entity.admin.Functionality@56ed25db]


答案 1

通过删除 CascadeType.MERGE on Permission 实体修复了此问题


答案 2

正确的解决方案是升级到休眠 4.2.15 / 4.3.6 或更高版本,并在持久性中添加以下行.xml:

<property name="hibernate.event.merge.entity_copy_observer" value="allow"/>


推荐