Remove association in relation to Many to Many

4

I have a one-way @manytomany fault relationship and I need to remove this association according to some criteria but I did not want to have to navigate all objects in the collection to remove one-by-one.

I thought of JQPL " delete from ... " but I do not know how to do it.

Note:

  • None of the objects will be deleted, only the association between them.
  • Work with MultiTenant with multiple Databases, where each client has its own database.
asked by anonymous 27.11.2014 / 13:58

2 answers

0

You can execute a delete or even update through JPQL using the createQuery of EntityManager method.

Example ( source ):

Query query = em.createQuery(
    "DELETE FROM EntidadeAssociacao t WHERE t.idOrigem = :idOrigem and t.idDestino = :idDestino");
int deletedCount = query
    .setParameter("idOrigem", 1)
    .setParameter("idDestino", 2)
    .executeUpdate();

However, it is important to remember that any such command or via native query (native query) directly affects the base, so entities in the JPA context will not immediately reflect the change.

If necessary, use the entityManager.refresh() method to update the entities.

    
27.11.2014 / 14:36
2

To delete just the association is simple. Assume the scenario below:

@ManyToMany(cascade = CascadeType.PERSIST) 
private List<Foo> foos;

If you remove a foos element and save the entity you will delete the record in the join table.

EDIT

I particularly do not like to get away from the ORM context. So if you go through the list and delete the elements one by one is a burden I can give you two alternatives:

  • If you can use java 8, use a lamda. With a single command you go through the entire list and remove what you want.
  • If Java 8 is not a solution, use utluiz's answer. She answers.
  • As I told you in the comments: This type of approach you are looking for is not cool because it creates the need to perform a delete and then refresh to refresh your entire session. which in the end will be less performative), in addition to leaving your system liable to error, as it will be dealing with detachados objects that can accidentally retachados , making your system inconsistent.

    Scrolling through the list, deleting the elements and then saving the object is less costly in most cases, since you are working in-memory most of the time, and more robust because you are not leaving of the ORM context.

    So if you're going to work in a different way than this, I suggest you look at whether JDBC will not serve you better.

        
    27.11.2014 / 14:25