2016-12-26 36 views
0

我執行到角色的實體用戶之間的單向一對多作爲https://examples.javacodegeeks.com/enterprise-java/jpa/one-to-many-unidirectional-mapping-in-jpa/單向一對多關係引起的UniqueConstraint

UserDataImpl.java解釋說:

@Entity 
public class UserDataImpl { 

    @Id 
    @GeneratedValue(strategy = GenerationType.AUTO) 
    private Long id; 

    . 
    . 
    . 

    @OneToMany(targetEntity = RoleDataImpl.class, cascade = CascadeType.ALL, orphanRemoval = true) 
    @JoinTable(name = "user_roles", joinColumns = @JoinColumn(name = "user_role_id"), inverseJoinColumns = @JoinColumn(name = "role_id")) 
    private Set<Role> roles = new HashSet<>(); 

    //Constructors 
    //Getters and setters 
    //Hashcode and equals 
    //toString 
} 

RoleDataImpl.java:

@Entity 
public class RoleDataImpl { 

    @Id 
    @GeneratedValue(strategy = GenerationType.AUTO) 
    private Long id; 

    private String name; 
    private byte permissionsInByte = 0; 

    //Constructors 
    //Getters and setters 
    //Hashcode and equals 
    //toString 
} 

我UserRepository和RoleRepository都擴展JpaRepository。我正在創建一個用戶對象並在保存之前將一個Role對象附加到它。

我得到在春天JPA的數據保存用戶以下錯誤:

org.springframework.dao.InvalidDataAccessApiUsageException: detached entity passed to persist: com.entity.impl.RoleDataImpl; nested exception is org.hibernate.PersistentObjectException: detached entity passed to persist: com.entity.impl.RoleDataImpl 
    . 
    . 

Caused by: org.hibernate.PersistentObjectException: detached entity passed to persist: com.wehub.entity.impl.RoleDataImpl 
    at org.hibernate.event.internal.DefaultPersistEventListener.onPersist(DefaultPersistEventListener.java:124) 
    at org.hibernate.internal.SessionImpl.firePersist(SessionImpl.java:765) 
    at org.hibernate.internal.SessionImpl.persist(SessionImpl.java:758) 
    . 
    . 

當我刪除了orphanRemoval和級聯:

@OneToMany(targetEntity = RoleDataImpl.class) 
    @JoinTable(name = "user_roles", joinColumns = @JoinColumn(name = "user_role_id"), inverseJoinColumns = @JoinColumn(name = "role_id")) 
    private Set<Role> roles = new HashSet<>(); 

我得到DataIntegrityException(第一個對象通常保存)。因爲user_roles表中的role_id將具有唯一的約束。但是我希望在刪除用戶時刪除user_roles條目。請幫忙。

回答

1

異常的消息告訴你什麼是錯的:com.entity.impl.RoleDataImpl這意味着你的User實例保存到Role參考這又不是你的EntityManager管理:通過堅持脫離實體。

它應該是這樣的:

Role detachedEntity = ...; // from somewhere else 

// obtain a managed entity 
// e.g. by name, use what you have at your disposal preferably the ID 
Role managedEntity = roleRepository.findByName(detachedEntity.getName()); 

// assuming you'd initialize a new User like so: 
User newUser = new UserDataImpl(); 
newUser.addRole(managedEntity); 

userRepository.save(newUser);