Last active
October 15, 2019 22:46
-
-
Save leewin12/8614127 to your computer and use it in GitHub Desktop.
Safely get Id from Hibernate Lazy Object
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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