Delete created entity from a Manytomany relation

Asked

Viewed 281 times

1

I have a relationship ManyToMany amid 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 is quiet, all entities are created in the bank and I already have some data.

Currently I make the method delete in 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 this::

How do I delete an item from the relationship user_profile? I don’t want to exclude the User nor the Profile, only one item of the relationship between the two.

1 answer

2


I believe that if you add a Scade in the Manytomany annotation would already solve the issue, take a look at this tutorial.

@ManyToMany(cascade = CascadeType.ALL)

[EDIT]

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

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

This way just remove the objects from the list of listaEntidadeFraca of Entidadeforte that no longer belong to it and make the update of Entidadeforte.

With this the rows created in the link table will also be removed.

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

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

Update: session.merge(entidadeForte);

Browser other questions tagged

You are not signed in. Login or sign up in order to post.