下面列出了怎么用org.hibernate.LazyInitializationException的API类实例代码及写法,或者点击链接到github查看源代码。
/**
* Asynchronously fetch an association that's configured for lazy loading.
*
* <pre>
* {@code Mutiny.fetch(author.getBook()).map(book -> print(book.getTitle()));}
* </pre>
*
* @param association a lazy-loaded association
*
* @return the fetched association, via a {@code Uni}
*
* @see org.hibernate.Hibernate#initialize(Object)
*/
static <T> Uni<T> fetch(T association) {
if ( association == null ) {
return Uni.createFrom().nullItem();
}
SharedSessionContractImplementor session;
if ( association instanceof HibernateProxy) {
session = ( (HibernateProxy) association ).getHibernateLazyInitializer().getSession();
}
else if ( association instanceof PersistentCollection) {
session = ( (AbstractPersistentCollection) association ).getSession();
}
else {
return Uni.createFrom().item( association );
}
if (session==null) {
throw new LazyInitializationException("session closed");
}
return Uni.createFrom().completionStage(
( (ReactiveSession) session ).reactiveFetch( association, false )
);
}
/**
* Asynchronously fetch an association that's configured for lazy loading.
*
* <pre>
* {@code Stage.fetch(author.getBook()).thenAccept(book -> print(book.getTitle()));}
* </pre>
*
* @param association a lazy-loaded association
*
* @return the fetched association, via a {@code CompletionStage}
*
* @see org.hibernate.Hibernate#initialize(Object)
*/
static <T> CompletionStage<T> fetch(T association) {
if ( association == null ) {
return CompletionStages.nullFuture();
}
SharedSessionContractImplementor session;
if ( association instanceof HibernateProxy) {
session = ( (HibernateProxy) association ).getHibernateLazyInitializer().getSession();
}
else if ( association instanceof PersistentCollection) {
session = ( (AbstractPersistentCollection) association ).getSession();
}
else {
return CompletionStages.completedFuture( association );
}
if (session==null) {
throw new LazyInitializationException("session closed");
}
return ( (ReactiveSession) session ).reactiveFetch( association, false );
}
@Override
public final void initialize() throws HibernateException {
if ( !initialized ) {
if ( allowLoadOutsideTransaction ) {
permissiveInitialization();
}
else if ( session == null ) {
throw new LazyInitializationException( "could not initialize proxy [" + entityName + "#" + id + "] - no Session" );
}
else if ( !session.isOpen() ) {
throw new LazyInitializationException( "could not initialize proxy [" + entityName + "#" + id + "] - the owning Session was closed" );
}
else if ( !session.isConnected() ) {
throw new LazyInitializationException( "could not initialize proxy [" + entityName + "#" + id + "] - the owning Session is disconnected" );
}
else {
target = session.immediateLoad( entityName, id );
initialized = true;
checkTargetState(session);
}
}
else {
checkTargetState(session);
}
}
@Test(expected = LazyInitializationException.class)
public void selectFromWithoutJoinFetch() {
log.info("... selectFromWithoutJoinFetch ...");
EntityManager em = emf.createEntityManager();
em.getTransaction().begin();
Author a = em.createQuery("SELECT a FROM Author a WHERE id = 1", Author.class).getSingleResult();
log.info("Commit transaction and close Session");
em.getTransaction().commit();
em.close();
try {
log.info(a.getFirstName()+" "+a.getLastName()+" wrote "+a.getBooks().size()+" books.");
} catch (Exception e) {
log.error(e);
throw e;
}
}
public final void initialize() throws HibernateException {
if (!initialized) {
if ( session==null ) {
throw new LazyInitializationException("could not initialize proxy - no Session");
}
else if ( !session.isOpen() ) {
throw new LazyInitializationException("could not initialize proxy - the owning Session was closed");
}
else if ( !session.isConnected() ) {
throw new LazyInitializationException("could not initialize proxy - the owning Session is disconnected");
}
else {
target = session.immediateLoad(entityName, id);
initialized = true;
checkTargetState();
}
}
else {
checkTargetState();
}
}
private void throwLazyInitializationException(Cause cause, LazyInitializationWork work) {
final String reason;
switch ( cause ) {
case NO_SESSION: {
reason = "no session and settings disallow loading outside the Session";
break;
}
case CLOSED_SESSION: {
reason = "session is closed and settings disallow loading outside the Session";
break;
}
case DISCONNECTED_SESSION: {
reason = "session is disconnected and settings disallow loading outside the Session";
break;
}
case NO_SF_UUID: {
reason = "could not determine SessionFactory UUId to create temporary Session for loading";
break;
}
default: {
reason = "<should never get here>";
}
}
final String message = String.format(
Locale.ROOT,
"Unable to perform requested lazy initialization [%s.%s] - %s",
work.getEntityName(),
work.getAttributeName(),
reason
);
throw new LazyInitializationException( message );
}
private void throwLazyInitializationException(String message) {
throw new LazyInitializationException(
"failed to lazily initialize a collection" +
(role == null ? "" : " of role: " + role) +
", " + message
);
}
public Object invoke(final Object proxy, final Method method, final Object[] args) throws Throwable {
if ( constructed ) {
Object result = invoke( method, args, proxy );
if ( result == INVOKE_IMPLEMENTATION ) {
Object target = getImplementation();
try {
final Object returnValue;
if ( ReflectHelper.isPublic( persistentClass, method ) ) {
if ( ! method.getDeclaringClass().isInstance( target ) ) {
throw new ClassCastException( target.getClass().getName() );
}
returnValue = method.invoke( target, args );
}
else {
if ( !method.isAccessible() ) {
method.setAccessible( true );
}
returnValue = method.invoke( target, args );
}
return returnValue == target ? proxy : returnValue;
}
catch ( InvocationTargetException ite ) {
throw ite.getTargetException();
}
}
else {
return result;
}
}
else {
// while constructor is running
if ( method.getName().equals( "getHibernateLazyInitializer" ) ) {
return this;
}
else {
throw new LazyInitializationException( "unexpected case hit, method=" + method.getName() );
}
}
}
protected final Object intercept(Object target, String fieldName, Object value) {
if ( initializing ) {
return value;
}
if ( uninitializedFields != null && uninitializedFields.contains( fieldName ) ) {
if ( session == null ) {
throw new LazyInitializationException( "entity with lazy properties is not associated with a session" );
}
else if ( !session.isOpen() || !session.isConnected() ) {
throw new LazyInitializationException( "session is not connected" );
}
final Object result;
initializing = true;
try {
result = ( ( LazyPropertyInitializer ) session.getFactory()
.getEntityPersister( entityName ) )
.initializeLazyProperty( fieldName, target, session );
}
finally {
initializing = false;
}
uninitializedFields = null; //let's assume that there is only one lazy fetch group, for now!
return result;
}
else {
return value;
}
}
/**
* Initialize the collection, if possible, wrapping any exceptions
* in a runtime exception
* @param writing currently obsolete
* @throws LazyInitializationException if we cannot initialize
*/
protected final void initialize(boolean writing) {
if (!initialized) {
if (initializing) {
throw new LazyInitializationException("illegal access to loading collection");
}
throwLazyInitializationExceptionIfNotConnected();
session.initializeCollection(this, writing);
}
}
private void throwLazyInitializationException(String message) {
throw new LazyInitializationException(
"failed to lazily initialize a collection" +
( role==null ? "" : " of role: " + role ) +
", " + message
);
}
@Test
public void testNPlusOne() {
List<PostComment> comments = null;
EntityManager entityManager = null;
EntityTransaction transaction = null;
try {
entityManager = entityManagerFactory().createEntityManager();
transaction = entityManager.getTransaction();
transaction.begin();
comments = entityManager.createQuery(
"select pc " +
"from PostComment pc " +
"where pc.review = :review", PostComment.class)
.setParameter("review", review)
.getResultList();
transaction.commit();
} catch (Throwable e) {
if ( transaction != null && transaction.isActive())
transaction.rollback();
throw e;
} finally {
if (entityManager != null) {
entityManager.close();
}
}
try {
for(PostComment comment : comments) {
LOGGER.info("The post title is '{}'", comment.getPost().getTitle());
}
} catch (LazyInitializationException expected) {
assertTrue(expected.getMessage().contains("could not initialize proxy"));
}
}
public Department getDepartment() {
Department dept = null;
try {
dept = this.getSubjectArea().getDepartment();
if(dept.toString()==null) {
}
}
catch (LazyInitializationException lie) {
new _RootDAO().getSession().refresh(this);
dept = this.getSubjectArea().getDepartment();
}
return (dept);
}
public Set<Location> getRooms() {
try {
return super.getRooms();
} catch (LazyInitializationException e) {
(new AssignmentDAO()).getSession().merge(this);
return super.getRooms();
}
}
@Deprecated
public String getHtmlHint(String preference) {
try {
if (!Hibernate.isPropertyInitialized(this, "roomType") || !Hibernate.isInitialized(getRoomType())) {
return LocationDAO.getInstance().get(getUniqueId()).getHtmlHintImpl(preference);
} else {
return getHtmlHintImpl(preference);
}
} catch (LazyInitializationException e) {
return LocationDAO.getInstance().get(getUniqueId()).getHtmlHintImpl(preference);
}
}
@Test(expected = LazyInitializationException.class)
public void find() {
Post post = postRepository.find(1L);
assertNotNull(post.getUser());
String email = post.getUser().getEmail();
assertNull(email);
}
@Test(expected = LazyInitializationException.class)
public void findWithEntityGraph_Comment_Without_User() {
Post post = postRepository.findWithEntityGraph(1L);
assertNotNull(post.getUser());
String email = post.getUser().getEmail();
assertNotNull(email);
assertNotNull(post.getComments());
assertEquals(post.getComments().size(), 2);
Comment comment = post.getComments().get(0);
assertNotNull(comment);
User user = comment.getUser();
user.getEmail();
}
@Override
public Object immediateLoad(String entityName, Serializable id) throws HibernateException {
throw new LazyInitializationException("reactive sessions do not support transparent lazy fetching"
+ " - use Session.fetch() (entity '" + entityName + "' with id '" + id + "' was not loaded)");
}
@Test(expected = LazyInitializationException.class)
public void whenCallNonTransactionalMethodWithPropertyOff_thenThrowException() {
serviceLayer.countAllDocsNonTransactional();
}
@Test
public void whenAccessUserRolesOutsideSession_thenThrownException() {
User detachedUser = createUserWithRoles();
Session session = sessionFactory.openSession();
session.beginTransaction();
User persistentUser = session.find(User.class, detachedUser.getId());
session.getTransaction().commit();
session.close();
thrown.expect(LazyInitializationException.class);
System.out.println(persistentUser.getRoles().size());
}