Skip to content

Instantly share code, notes, and snippets.

@leewin12
Last active October 15, 2019 22:46
Show Gist options
  • Star 4 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save leewin12/8614127 to your computer and use it in GitHub Desktop.
Save leewin12/8614127 to your computer and use it in GitHub Desktop.
Safely get Id from Hibernate Lazy Object
import org.hibernate.proxy.HibernateProxy;
import org.hibernate.proxy.LazyInitializer;
import com.ngr.api.model.BaseModel;
/**
*
* public interface BaseModel<T> {
* public T getId();
* }
*
* @author Greg
*
*/
public class HibernateUtil {
@SuppressWarnings("unchecked")
public static <T> T getIdFromLazyObject(BaseModel<T> entity) {
if (entity == null) {
return null;
}
if (entity instanceof HibernateProxy) {
LazyInitializer lazyInitializer = ((HibernateProxy) entity).getHibernateLazyInitializer();
if (lazyInitializer.isUninitialized()) {
return (T) lazyInitializer.getIdentifier();
}
}
return entity.getId();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment