Search code examples
jpajpa-2.1

Force JPA entity to be updated in database (after it was already inserted)


Suppose an entity which bears a Map<String, Object>. Such Map is serialized as JSON (per custom AttributeConverter [code not listed here]). Like this:

@Entity
@Table(...)
public class MyEntity {
  @Column(...)
  private Map<String, Object> aMap;
  /* ... */

The whole thing is working fine. Converter gets called both to insert a new entity; and to load a previous entity.

Now the insert procedure is evolving to get more complicated. For reasons beyond my will (aka framework), the entity is forced (aka flush()) to be inserted with an initial [almost correct] Map.

Before the transaction ends, this Map undergoes some changes (in values only, not in keys, not that it matters).

I expect that JPA provider to somehow see these changes (through Map's hashcode/equals perhaps) and to update the database. But in fact it misses the changes.

Is it possible to tell JPA: hey, this entity is dirty [I know it is, nevermind your opinion about that], do persist it again in the database?

Note: some values in the Map are other entities (which is no problem to the JSON converter), and the changes the Map undergoes is exactly in those entities, in their PKs, but maybe maybe hashcode/equals is not sensitized to those changes.


Solution

  • Try detach and merge :

    EntityManager em;
    MyEntity myEntity;
    
    //myEntity becomes dirty
    em.detach(myEntity);
    myEntity = em.merge(myEntity);
    

    If you want to keep the same object, try remove, persist :

    em.remove(myEntity);
    em.persist(myEntity);