HibernateUtils.java

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

  2. import no.nav.data.common.exceptions.TechnicalException;
  3. import org.hibernate.proxy.HibernateProxy;
  4. import org.hibernate.proxy.LazyInitializer;
  5. import org.springframework.data.util.ReflectionUtils;

  6. import java.util.UUID;

  7. public final class HibernateUtils {

  8.     private HibernateUtils() {
  9.     }

  10.     /**
  11.      * Get id without loading the entity
  12.      */
  13.     @SuppressWarnings("unchecked")
  14.     public static UUID getId(Object entity) {
  15.         if (entity instanceof HibernateProxy hp) {
  16.             LazyInitializer lazyInitializer = hp.getHibernateLazyInitializer();
  17.             if (lazyInitializer.isUninitialized()) {
  18.                 return (UUID) lazyInitializer.getIdentifier();
  19.             }
  20.         }
  21.         try {
  22.             return (UUID) ReflectionUtils.findRequiredMethod(entity.getClass(), "getId").invoke(entity);
  23.         } catch (Exception e) {
  24.             throw new TechnicalException("id error", e);
  25.         }
  26.     }

  27. }