Search code examples
javajpaeclipselinkone-to-manyentitymanager

removing entity with unidirectional relationship @ManyToOne (JPA)


I have problem, becouse I don't know how to remove specific role from User. This problem is connected with unidirectional relation in Permission class. These are only relevant code snippets.

Class Person

@Entity
public class User {

@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long userId;

@OneToMany(cascade = CascadeType.ALL, fetch=FetchType.LAZY, mappedBy="user")
private Collection<Role> roles;

Class Role

@Entity
public class Role {

@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long roleId;

@ManyToOne( fetch=FetchType.LAZY)
private User user;

I tried to remove specific Role from User in this way

user.getRoles().remove(roleToRemove)
entityManger.merge(user)

roleToRemove was deleted from Collection but not from datebase. (I wrote test which were completed)

So, i added

 orphanRemoval = true

And currently I have problem with unidirectional relationship which occurs in Permission class. I receives DatabaseExepction becouse idRole which I want remove, exists in Permision table.

 @Entity
public class Permission {

@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long permissionId;

@ManyToOne( fetch=FetchType.LAZY)
private Role role;

So, My question is how to manage with this problem.


Solution

  • Hello the User is not the owner of the relationship User - Role. You need to update the owning end of the relationship in order to make it work.

    user.getRoles().remove(roleToRemove)
    roleToRemove.setUser(null)
    entityManger.merge(user)
    

    My understanding is that you don't need orphan removal.