Delete created entity from a ManyToMany relation

1

I have a ManyToMany relation between users and profiles mapped with Hibernate :

user:

id
name

profile:

id
profile_name

user_profile:

user_id
profile_id

The mapping is done as follows:

User:

@ManyToMany(fetch = FetchType.EAGER)
private List<Profile> profiles = new ArrayList<>();

Profile

@ManyToMany(fetch = FetchType.EAGER, mappedBy = "profiles")
private List<User> users= new ArrayList<>();

So far, it's cool, all entities are created in the database and I already have some data persisted in them.

I currently do the delete method this way:

public void excluir(T entity) {
        Session session = HibernateUtil.getSessionFactory().openSession();
        Transaction transacao = null;
        try {
            transacao = session.beginTransaction();
            session.delete(entity);
            transacao.commit();
        } catch (RuntimeException e) {
            if (transacao != null)
                transacao.rollback();
            throw e;
        } finally {
            session.close();
        }
    }

My question is:

  

How do I delete an item from the user_profile relation? I do not want   exclude User and Profile , only one item in the relationship between the two.

    
asked by anonymous 09.06.2016 / 18:22

1 answer

2

I believe that if you add a cascade in the ManyToMany annotation it would already resolve the issue, take a look at this tutorial .

@ManyToMany(cascade = CascadeType.ALL)

[EDIT]

An example of a project that I have here and this works is mapped the @ManyToMany relationship as follows (unidirectional):

@ManyToMany(fetch = FetchType.EAGER) 
@JoinTable(name = "tabelarelacional", joinColumns = @JoinColumn(name = "id_entidadeforte"),
     inverseJoinColumns = @JoinColumn(name = "id_entidadefraca")) 
private Set<EntidadeFraca> listaEntidadeFraca;

That way you just need to remove the objects from the listaEntidadeFraca list of the EntityFort that no longer belong to it and update the Entitystrong.

With this the lines created in the connection table will also be removed.

Example: entidadeForte = {id:1, listaEntidadeFraca:[ entidadeFraca1, entidadeFraca2]}

Removing: entidadeForte = {id:1, listaEntidadeFraca:[ entidadeFraca1]}

Update : session.merge(entidadeForte);

    
10.06.2016 / 15:13