0

I use spring data and hibernate. I have an Entity (TestEntity). I made a custom hibernate type that deserializes one String field to two columns. If I persist an entity and then change it everything works fine and hibernate sends update query (it makes my type work and update query to DB "splits" my old column to two new). But my goal is to make this king of migration for every record. I can't use an ordinary DB migration because there is some logic in my custom type. I want to make something like this:

// here I persist all my entities
List<TestEntity> entities = entityRepository.findAll();
for (TestEntity entity : entities) {
   // This piece of code does nothing, because when hibernate merges two entities, it understands, that nothing changed, so it won't send update query. 
   entityRepository.save(entity);
}

But I want him to send update query, although nothing has changed. Moreover, I want this hibernate behaviour to be in one place only (for example, I will create controller to execute this DB update). What is a solution to my problem? Is there any approach to its solving?

  • I don't understand, why do you need to run an update query if nothing has changed? – Davide D'Alto Apr 02 '21 at 16:55
  • What I don't understand is if there's new mapping logic to one of the properties, how can `findAll` and `save` both work correctly in your example? – crizzis Apr 03 '21 at 12:29
  • Also, what DB migration tool are you using? Liquibase, for example, allows you to create migrations written in Java, so you could call your custom logic inside and *still* be able to execute SQL afterwards – crizzis Apr 03 '21 at 12:31

1 Answers1

1

I don't understand why you need it but you need to detach the entity from the session for this to work.

As far as I understand, you need the EntityManger:

    @PersistenceContext
    private EntityManager entityManager;

    ...

    List<TestEntity> entities = entityRepository.findAll();
    for (TestEntity entity : entities) {
      entityManager.detach(entity);
      entityRepository.save(entity); // or entityManager.unwrap(Session.class).saveOrUpdate();
   }
   

See Spring JpaRepository - Detach and Attach entity

Davide D'Alto
  • 7,421
  • 2
  • 16
  • 30