JpaConfig.java

  1. package no.nav.data.common.jpa;

  2. import io.prometheus.client.hibernate.HibernateStatisticsCollector;
  3. import jakarta.persistence.EntityManagerFactory;
  4. import lombok.extern.slf4j.Slf4j;
  5. import no.nav.data.AppStarter;
  6. import no.nav.data.common.auditing.AuditVersionListener;
  7. import no.nav.data.common.auditing.AuditorAwareImpl;
  8. import no.nav.data.common.auditing.domain.AuditVersionRepository;
  9. import no.nav.data.common.storage.StorageService;
  10. import org.hibernate.SessionFactory;
  11. import org.springframework.boot.ApplicationRunner;
  12. import org.springframework.boot.autoconfigure.domain.EntityScan;
  13. import org.springframework.context.annotation.Bean;
  14. import org.springframework.context.annotation.Configuration;
  15. import org.springframework.context.annotation.DependsOn;
  16. import org.springframework.data.domain.AuditorAware;
  17. import org.springframework.data.jpa.repository.config.EnableJpaAuditing;
  18. import org.springframework.data.jpa.repository.config.EnableJpaRepositories;


  19. import static no.nav.data.common.utils.MdcUtils.wrapAsync;

  20. @Slf4j
  21. @EntityScan(basePackageClasses = AppStarter.class)
  22. @EnableJpaRepositories(basePackageClasses = AppStarter.class)
  23. @Configuration
  24. @EnableJpaAuditing(auditorAwareRef = "auditorAware")
  25. public class JpaConfig {

  26.     @Bean
  27.     public AuditorAware<String> auditorAware() {
  28.         return new AuditorAwareImpl();
  29.     }

  30.     @Bean
  31.     public ApplicationRunner initAudit(AuditVersionRepository repository) {
  32.         return args -> AuditVersionListener.setRepo(repository);
  33.     }

  34.     @Bean
  35.     @DependsOn("initAudit")
  36.     public ApplicationRunner migrate(StorageService storage) {
  37.         return (args) -> wrapAsync(() -> {
  38.             log.debug("Running migrations");
  39.         }, "Database migration")
  40.                 .run();
  41.     }

  42.     @Bean
  43.     public ApplicationRunner initHibernateMetrics(EntityManagerFactory emf) {
  44.         return args -> new HibernateStatisticsCollector(emf.unwrap(SessionFactory.class), "main").register();
  45.     }
  46. }