I'm having problems deleting a @ManyToMany relationship in JPA. In short, I have 3 tables: USER, PERMISSION, and USER_PERMISSION that is the relationship of the previous ones, the relationship is N to N. The problem is that I'm not sure how to remove or add a new permission to an existing user in the base, follows simplified model:
@Entity
@Table(name="TB_USUARIO")
public class Usuario {
@Id
@Column(name="NO_USUARIO", unique=true, nullable=false, length=50)
private String noUsuario;
@ManyToMany
@JoinTable(
name="TB_USUARIO_PERMISSAO"
, joinColumns={
@JoinColumn(name="NO_USUARIO", nullable=false)
}
, inverseJoinColumns={
@JoinColumn(name="NO_METODO", referencedColumnName="NO_METODO", nullable=false),
@JoinColumn(name="NO_PERMISSAO", referencedColumnName="NO_PERMISSAO", nullable=false))
}
)
private List<Permissao> permissoes;
}
@Entity
@Table(name="TB_PERMISSAO")
public class Permissao {
@EmbeddedId
private PermissaoPK id;
@ManyToMany(mappedBy="permissoes")
private List<Usuario> usuarios;
}
My problem is with the Permissions field mapping of the User class, when I insert a new User into the database, adding the permission works, p>
Usuario usuario = new Usuario("USUARIO_01");
usuario.getPermissoes().add(permissao); //permissao ja cadastrada no banco
entityManager.persist(usuario);
This code correctly inserts a new user and also the relationship with the permission in the TB_USUARIO_PERMISSAO table. The problem now is to delete the permissions, let's assume that a user has 2 permissions and I want to delete one of them, how do I do that? Here's an example does not work :
Usuario usuario = entityManager.find(Usuario.class, "USUARIO_01");
usuario.getPermissoes().remove(0);
entityManager.merge(usuario);
This code above does not work, do I have to change the mapping, I know, perhaps creating a UserPermission? The mapping is the way the reverse engineering engine created. If I remove a user, the permissions are automatically deleted. My problem is to delete and also add a new permission from a user already registered in the bank. I've also used Cascade and to no avail.
Can you help?
Note: to simplify I changed the code by the editor, may have some error that if put in the IDE will not compile, the idea is to show the base. I also tried other ways to remove / add that I thought it best not to quote since they did not work
Thank you!