Home > Software engineering >  Hibernate Entity attribute injection
Hibernate Entity attribute injection

Time:01-14

I have a monolitic application with a monolitic database that has many tables.

One of its tables is a user table with some columns (email, city, contract...). I am in the middle of a migration of the user to a user microservice and I am migrating those attributes little by little.

I have started migrating city and contract, so my user microservice has its own database with only those attributes.

I need to start using the data of the user microservice for those attributes in my monolitic application instead of the data of my monolitic database.

The Entity of my monolitic application looks like:

@Entity
@Table(name = "User")
public class User {

    @Column(name = "email")
    private String email; -- Need monolitic DB data
    
    @Column(name = "contract_id")
    private Long contractId; -- Need user microservice data

    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "city_id", nullable = false, foreignKey = @ForeignKey(name = "user_city_id_city_id_fk"))
    private City city; -- Need microservice data

    ...getters and setters

}

I need to modify the default behaviour of the lazy loading of the city in order to obtain the city object from a REST API GET call ignoring the data of the city from the database of my monolitic application when I call getCity() for the first time.

I need to obtain the contractId from a REST API GET call instead of the monolitic database contractId.

I need to obtain the email attribute from my monolitic DB.

I know that Hibernate uses proxyes to obtain the data from the database when objects are lazy loaded for the first time using their getters, so I would like to know if it is possible to change that default behaviour in order to insert my API calls and how could I do it.

EDIT: I have read that hibernate allows to define interceptors. One of the methods is onl oad. Would be a good idea to define an interceptor, detect the user class and inject my api call responses in the city and contract attributes?

CodePudding user response:

You can take advantage of interceptors or event listeners. I've done some tests and maybe the listener which could fit here is post-load event listener.

Using the code you attach, this could be a solution:

public class PostLoadCustomEventListener implements PostLoadEventListener {

    private final YourMicroservice yourMicroservice;

    ...

    @Override
    public void onPostLoad(PostLoadEvent event) {
        if(event.getEntity() instance of User) {
          Long cityId = this.yourMicroservice.getCityId();

          LazyInitializer cityHibernateProxy =((HibernateProxy)entity.getCity())
            .getHibernateLazyInitializer();
          cityHibernateProxy.setIdentifier(cityId);
       } 
   }

}

Here you can check how to configure an event listener.

  • Related