org.hibernate.LazyInitializationException Java Examples

The following examples show how to use org.hibernate.LazyInitializationException. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: Mutiny.java    From hibernate-reactive with GNU Lesser General Public License v2.1 6 votes vote down vote up
/**
 * 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 )
	);
}
 
Example #2
Source File: Stage.java    From hibernate-reactive with GNU Lesser General Public License v2.1 6 votes vote down vote up
/**
 * 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 );
}
 
Example #3
Source File: AbstractLazyInitializer.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
@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);
	}
}
 
Example #4
Source File: TestJoinFetch.java    From HibernateTips with MIT License 6 votes vote down vote up
@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;
	}
}
 
Example #5
Source File: AbstractLazyInitializer.java    From cacheonix-core with GNU Lesser General Public License v2.1 6 votes vote down vote up
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();
	}
}
 
Example #6
Source File: PostRepositoryIntegrationTest.java    From tutorials with MIT License 5 votes vote down vote up
@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();
}
 
Example #7
Source File: PostRepositoryIntegrationTest.java    From tutorials with MIT License 5 votes vote down vote up
@Test(expected = LazyInitializationException.class)
public void find() {
    Post post = postRepository.find(1L);
    assertNotNull(post.getUser());
    String email = post.getUser().getEmail();
    assertNull(email);
}
 
Example #8
Source File: Location.java    From unitime with Apache License 2.0 5 votes vote down vote up
@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);
}
  }
 
Example #9
Source File: Assignment.java    From unitime with Apache License 2.0 5 votes vote down vote up
public Set<Location> getRooms() {
	try {
		return super.getRooms();
	} catch (LazyInitializationException e) {
		(new AssignmentDAO()).getSession().merge(this);
		return super.getRooms();
	}
}
 
Example #10
Source File: CourseOffering.java    From unitime with Apache License 2.0 5 votes vote down vote up
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);
}
 
Example #11
Source File: LazyInitializationExceptionTest.java    From high-performance-java-persistence with Apache License 2.0 5 votes vote down vote up
@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"));
    }
}
 
Example #12
Source File: AbstractPersistentCollection.java    From cacheonix-core with GNU Lesser General Public License v2.1 5 votes vote down vote up
private void throwLazyInitializationException(String message) {
	throw new LazyInitializationException(
			"failed to lazily initialize a collection" + 
			( role==null ?  "" : " of role: " + role ) + 
			", " + message
		);
}
 
Example #13
Source File: AbstractPersistentCollection.java    From cacheonix-core with GNU Lesser General Public License v2.1 5 votes vote down vote up
/**
 * 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);
	}
}
 
Example #14
Source File: AbstractFieldInterceptor.java    From cacheonix-core with GNU Lesser General Public License v2.1 5 votes vote down vote up
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;
	}
}
 
Example #15
Source File: CGLIBLazyInitializer.java    From cacheonix-core with GNU Lesser General Public License v2.1 5 votes vote down vote up
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() );
		}
	}
}
 
Example #16
Source File: AbstractPersistentCollection.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
private void throwLazyInitializationException(String message) {
	throw new LazyInitializationException(
			"failed to lazily initialize a collection" +
					(role == null ? "" : " of role: " + role) +
					", " + message
	);
}
 
Example #17
Source File: Helper.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
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 );
}
 
Example #18
Source File: LazyLoadNoTransPropertyOffIntegrationTest.java    From tutorials with MIT License 4 votes vote down vote up
@Test(expected = LazyInitializationException.class)
public void whenCallNonTransactionalMethodWithPropertyOff_thenThrowException() {
    serviceLayer.countAllDocsNonTransactional();
}
 
Example #19
Source File: HibernateNoSessionUnitTest.java    From tutorials with MIT License 4 votes vote down vote up
@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());
}
 
Example #20
Source File: ReactiveSessionImpl.java    From hibernate-reactive with GNU Lesser General Public License v2.1 4 votes vote down vote up
@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)");
}