1

I was getting an error like this

a different object with the same identifier value was already associated with the session:

I've searched and found that it could be fixed with CascadeType.MERGE or refactoring a lot of code to prevent that a same database object becomes two instances within the session.

I can't refactor it.

CascadeType.MERGE worked, but that means I would have to code a lot to resolve remove problems, since it was .ALL before, right?

I got it working putting

@Transactional(propagation = Propagation.REQUIRES_NEW)

above a method, of a class annoted with @Service, that query database, which was the one that was throwing the exception I mentioned.

I need help to understand if this new annotated method can bring me any future headache like it is now.

It is being called from some cron jobs beside the action I'm fixing.

luizfzs
  • 1,328
  • 2
  • 18
  • 34
Ramon Marques
  • 3,046
  • 2
  • 23
  • 34

2 Answers2

2

In fact you create a separate transaction for the method call by annotating the method with @Transactional(propagation = Propagation.REQUIRES_NEW)

It means in case of an Exception thrown out of the method all DB changes (saving etc.) are applied and are not rolled back. This could significantly damage the business logic and could be source of inconsistent data in DB.

I would reconsider applying the Propagation.REQUIRES_NEW.

Merge sounds much more suitable in this case.

StanislavL
  • 56,971
  • 9
  • 68
  • 98
1

None of the solution you listed are acceptable IMHO.

Deferring some part of treatment to a new transaction will break the atomicity (all or nothing) of your unit of work, and changing the cascading type will imply that you manually handle all operation automatically cascaded before.

The right approach is to understand why hibernate encounters 2 different object instances with the same identifier, the most common causes is because you manually persists (save) a detached / transient object with a fixed identifier while this one already exists in the session (a managed object with the same identifier is already in the session).

You could try to manually re-attach (merge / update /saveOrUpdate) the detached object instance causing the problem.

You have to be aware of the entity lifecycle to properly understand what happens here.

Gab
  • 7,869
  • 4
  • 37
  • 68