How to use EntityListeners with flyway migration?

53 views Asked by At

Simply I need an answer for why it is not working and find an alternative if this is not possible.

I am using entity listeners annotation, which helps me catch events around changes with my database tables where I trigger my "business things".

Code example:

@EntityListeners(MyClassEntityListener.class)
@Entity
public final class EntityClass {
  //... attribs. here
}

public class MyClassEntityListener {
  @PostUpdate
  @PostPersist
  void onUpdate(EntityClass entityClass) {
    // ... business here -> this is not called with flyway migrations
  }
}

Flyway migration example:

insert into entity_class (uuid, ...) values
('c8297c38-04e4-48ed-afb6-070c8d994d54', ...);

Everything works fine, if I create/update entities through controllers with API as hibernate and transactions are used there. With flyway migration, this is not working - a row is created and the listener is not called. The simple question is why and how to make a workaround.

I do not want to use flyway callbacks, because one migration file can contain many new entities and I need to call my onchange/onupdate callback for every entity.

I am using mysql as database and flyway version 8.5.0, springboot version 2.7.3 and java 17.

1

There are 1 answers

1
Per Huss On

JPA will manage your EntityListeners. The flyway migration SQL script will use a database connection and send SQL to the database, which JPA will not be aware of. You may want to have a look at the Flyway migration documentation on the section of "Java-based migration", in which you can assemble the relevant part of your application for the entity listeners to work, and then use JPA to manipulate your database content. Good luck!