Search in sources :

Example 1 with LazyInitializationException

use of org.hibernate.LazyInitializationException in project hibernate-orm by hibernate.

the class AbstractLazyInitializer method permissiveInitialization.

protected void permissiveInitialization() {
    if (session == null) {
        // we have a detached collection thats set to null, reattach
        if (sessionFactoryUuid == null) {
            throw new LazyInitializationException("could not initialize proxy - no Session");
        }
        try {
            SessionFactoryImplementor sf = (SessionFactoryImplementor) SessionFactoryRegistry.INSTANCE.getSessionFactory(sessionFactoryUuid);
            SharedSessionContractImplementor session = (SharedSessionContractImplementor) sf.openSession();
            session.getPersistenceContext().setDefaultReadOnly(true);
            session.setFlushMode(FlushMode.MANUAL);
            boolean isJTA = session.getTransactionCoordinator().getTransactionCoordinatorBuilder().isJta();
            if (!isJTA) {
                // Explicitly handle the transactions only if we're not in
                // a JTA environment.  A lazy loading temporary session can
                // be created even if a current session and transaction are
                // open (ex: session.clear() was used).  We must prevent
                // multiple transactions.
                session.beginTransaction();
            }
            try {
                target = session.immediateLoad(entityName, id);
                initialized = true;
                checkTargetState(session);
            } finally {
                // make sure the just opened temp session gets closed!
                try {
                    if (!isJTA) {
                        session.getTransaction().commit();
                    }
                    session.close();
                } catch (Exception e) {
                    LOG.warn("Unable to close temporary session used to load lazy proxy associated to no session");
                }
            }
        } catch (Exception e) {
            LOG.error("Initialization failure", e);
            throw new LazyInitializationException(e.getMessage());
        }
    } else if (session.isOpen() && session.isConnected()) {
        target = session.immediateLoad(entityName, id);
        initialized = true;
        checkTargetState(session);
    } else {
        throw new LazyInitializationException("could not initialize proxy - Session was closed or disced");
    }
}
Also used : LazyInitializationException(org.hibernate.LazyInitializationException) SessionFactoryImplementor(org.hibernate.engine.spi.SessionFactoryImplementor) SharedSessionContractImplementor(org.hibernate.engine.spi.SharedSessionContractImplementor) SessionException(org.hibernate.SessionException) TransientObjectException(org.hibernate.TransientObjectException) LazyInitializationException(org.hibernate.LazyInitializationException) HibernateException(org.hibernate.HibernateException)

Example 2 with LazyInitializationException

use of org.hibernate.LazyInitializationException in project hibernate-orm by hibernate.

the class PersistOnLazyCollectionTest method testPersistOnAlreadyPersistentEntityWithUninitializedLazyCollection.

@Test
@TestForIssue(jiraKey = "HHH-11916")
public void testPersistOnAlreadyPersistentEntityWithUninitializedLazyCollection() {
    final Invoice _invoice = doInHibernate(this::sessionFactory, this::createInvoiceWithTwoInvoiceLines);
    Invoice invoiceAfter = doInHibernate(this::sessionFactory, session -> {
        SessionStatistics stats = session.getStatistics();
        // load invoice, invoiceLines should not be loaded
        Invoice invoice = session.get(Invoice.class, _invoice.getId());
        Assert.assertEquals("Invoice lines should not be initialized while loading the invoice, " + "because of the lazy association.", 1, stats.getEntityCount());
        invoice.setName(invoice.getName() + " !");
        return invoice;
    });
    try {
        invoiceAfter.getInvoiceLines().size();
        fail("Should throw LazyInitializationException");
    } catch (LazyInitializationException expected) {
    }
}
Also used : SessionStatistics(org.hibernate.stat.SessionStatistics) LazyInitializationException(org.hibernate.LazyInitializationException) Test(org.junit.Test) TestForIssue(org.hibernate.testing.TestForIssue)

Example 3 with LazyInitializationException

use of org.hibernate.LazyInitializationException in project OpenOLAT by OpenOLAT.

the class RepositoryManagerTest method lazyLoadingCheck.

/**
 * This is a simulation of OO-2667 to make sure that the LazyInitializationException don't
 * set the transaction on rollback.
 */
@Test
public void lazyLoadingCheck() {
    RepositoryEntry re = repositoryService.create("Rei Ayanami", "-", "Repository entry DAO Test 5", "", null);
    dbInstance.commitAndCloseSession();
    RepositoryEntryLifecycle cycle = lifecycleDao.create("New cycle 1", "New cycle soft 1", false, new Date(), new Date());
    re = repositoryManager.setDescriptionAndName(re, "Updated repo entry", null, null, "", null, null, null, null, null, null, cycle);
    dbInstance.commitAndCloseSession();
    RepositoryEntry lazyRe = repositoryManager.setAccess(re, 2, false);
    dbInstance.commitAndCloseSession();
    try {
        // produce the exception
        lazyRe.getLifecycle().getValidFrom();
        Assert.fail();
    } catch (LazyInitializationException e) {
    // 
    }
    // load a fresh entry
    RepositoryEntry entry = repositoryManager.lookupRepositoryEntry(lazyRe.getKey());
    Date validFrom = entry.getLifecycle().getValidFrom();
    Assert.assertNotNull(validFrom);
    dbInstance.commitAndCloseSession();
}
Also used : RepositoryEntryLifecycle(org.olat.repository.model.RepositoryEntryLifecycle) LazyInitializationException(org.hibernate.LazyInitializationException) Date(java.util.Date) Test(org.junit.Test)

Example 4 with LazyInitializationException

use of org.hibernate.LazyInitializationException in project jbpm by kiegroup.

the class ProcessServiceWithEntitiesTest method testStartProcessAndGetVariables.

@Test
public void testStartProcessAndGetVariables() {
    assertNotNull(deploymentService);
    KModuleDeploymentUnit deploymentUnit = new KModuleDeploymentUnit(GROUP_ID, ARTIFACT_ID, VERSION);
    deploymentService.deploy(deploymentUnit);
    units.add(deploymentUnit);
    boolean isDeployed = deploymentService.isDeployed(deploymentUnit.getIdentifier());
    assertTrue(isDeployed);
    assertNotNull(processService);
    Map<String, Object> params = new HashMap<String, Object>();
    long processInstanceId = processService.startProcess(deploymentUnit.getIdentifier(), "processvarentity", params);
    assertNotNull(processInstanceId);
    ProcessInstance pi = processService.getProcessInstance(processInstanceId);
    assertNotNull(pi);
    Map<String, Object> variables = processService.getProcessInstanceVariables(processInstanceId);
    assertNotNull(variables);
    assertEquals(1, variables.size());
    assertTrue(variables.containsKey("caseDetails"));
    VariableEntity varEntity = (VariableEntity) variables.get("caseDetails");
    // make sure getting mapped variables does NOT throw LazyInitializationException
    Set<MappedVariable> mappedVariables = varEntity.getMappedVariables();
    try {
        assertEquals(1, mappedVariables.size());
        MappedVariable mappedVariable = mappedVariables.iterator().next();
        assertEquals("example.CaseDetail", mappedVariable.getVariableType());
    } catch (LazyInitializationException e) {
        fail("Unable to retrieve mapped variables : " + e.getMessage());
    }
}
Also used : VariableEntity(org.drools.persistence.jpa.marshaller.VariableEntity) HashMap(java.util.HashMap) LazyInitializationException(org.hibernate.LazyInitializationException) ProcessInstance(org.kie.api.runtime.process.ProcessInstance) MappedVariable(org.drools.persistence.jpa.marshaller.MappedVariable) KModuleDeploymentUnit(org.jbpm.kie.services.impl.KModuleDeploymentUnit) AbstractKieServicesBaseTest(org.jbpm.kie.test.util.AbstractKieServicesBaseTest) Test(org.junit.Test)

Example 5 with LazyInitializationException

use of org.hibernate.LazyInitializationException in project Gemma by PavlidisLab.

the class AuditAdvice method processAssociations.

/**
 * Fills in audit trails on newly created child objects after a 'create' or 'update'. It does not add 'update'
 * events on the child objects.
 * Thus if the update is on an expression experiment that has a new Characteristic, the Characteristic will have a
 * 'create' event, and the EEE will get an added update event (via the addUpdateAuditEvent call elsewhere, not here)
 *
 * @see AclAdvice for similar code for ACLs
 */
private void processAssociations(String methodName, Object object, User user) {
    if (object instanceof AuditTrail)
        // don't audit audit trails.
        return;
    EntityPersister persister = crudUtils.getEntityPersister(object);
    if (persister == null) {
        throw new IllegalArgumentException("No persister found for " + object.getClass().getName());
    }
    CascadeStyle[] cascadeStyles = persister.getPropertyCascadeStyles();
    String[] propertyNames = persister.getPropertyNames();
    try {
        for (int j = 0; j < propertyNames.length; j++) {
            CascadeStyle cs = cascadeStyles[j];
            String propertyName = propertyNames[j];
            if (!this.specialCaseForAssociationFollow(object, propertyName) && (this.canSkipAssociationCheck(object, propertyName) || !crudUtils.needCascade(methodName, cs))) {
                continue;
            }
            PropertyDescriptor descriptor = BeanUtils.getPropertyDescriptor(object.getClass(), propertyName);
            Object associatedObject = ReflectionUtil.getProperty(object, descriptor);
            if (associatedObject == null)
                continue;
            Class<?> propertyType = descriptor.getPropertyType();
            if (AbstractAuditable.class.isAssignableFrom(propertyType)) {
                AbstractAuditable auditable = (AbstractAuditable) associatedObject;
                try {
                    this.maybeAddCascadeCreateEvent(object, auditable, user);
                    this.processAssociations(methodName, auditable, user);
                } catch (LazyInitializationException e) {
                    // be necessary.
                    if (AuditAdvice.log.isDebugEnabled())
                        AuditAdvice.log.debug("Caught lazy init error while processing " + auditable + ": " + e.getMessage() + " - skipping creation of cascade event.");
                }
            } else if (Collection.class.isAssignableFrom(propertyType)) {
                Collection<?> associatedObjects = (Collection<?>) associatedObject;
                try {
                    Hibernate.initialize(associatedObjects);
                    for (Object collectionMember : associatedObjects) {
                        if (AbstractAuditable.class.isAssignableFrom(collectionMember.getClass())) {
                            AbstractAuditable auditable = (AbstractAuditable) collectionMember;
                            try {
                                Hibernate.initialize(auditable);
                                this.maybeAddCascadeCreateEvent(object, auditable, user);
                                this.processAssociations(methodName, collectionMember, user);
                            } catch (LazyInitializationException e) {
                                if (AuditAdvice.log.isDebugEnabled())
                                    AuditAdvice.log.debug("Caught lazy init error while processing " + auditable + ": " + e.getMessage() + " - skipping creation of cascade event.");
                            // If this happens, it means the object can't be 'new' so adding audit trail can't
                            // be necessary. But keep checking.
                            }
                        }
                    }
                } catch (LazyInitializationException e) {
                    // be necessary.
                    if (AuditAdvice.log.isDebugEnabled())
                        AuditAdvice.log.debug("Caught lazy init error while processing " + object + ": " + e.getMessage() + " - skipping creation of cascade event.");
                }
            }
        }
    } catch (IllegalAccessException | InvocationTargetException e) {
        throw new RuntimeException(e);
    }
}
Also used : EntityPersister(org.hibernate.persister.entity.EntityPersister) CascadeStyle(org.hibernate.engine.CascadeStyle) PropertyDescriptor(java.beans.PropertyDescriptor) AbstractAuditable(ubic.gemma.model.common.AbstractAuditable) JoinPoint(org.aspectj.lang.JoinPoint) InvocationTargetException(java.lang.reflect.InvocationTargetException) LazyInitializationException(org.hibernate.LazyInitializationException) Collection(java.util.Collection) AuditTrail(ubic.gemma.model.common.auditAndSecurity.AuditTrail)

Aggregations

LazyInitializationException (org.hibernate.LazyInitializationException)15 Test (org.junit.Test)13 Session (org.hibernate.Session)5 TestForIssue (org.hibernate.testing.TestForIssue)4 TransactionStatus (org.springframework.transaction.TransactionStatus)3 Date (java.util.Date)2 List (java.util.List)2 SessionStatistics (org.hibernate.stat.SessionStatistics)2 TransactionCallback (org.springframework.transaction.support.TransactionCallback)2 BagBranch (com.vladmihalcea.hibernate.model.baglist.BagBranch)1 BagForest (com.vladmihalcea.hibernate.model.baglist.BagForest)1 BagLeaf (com.vladmihalcea.hibernate.model.baglist.BagLeaf)1 BagTree (com.vladmihalcea.hibernate.model.baglist.BagTree)1 Branch (com.vladmihalcea.hibernate.model.indexlist.Branch)1 Forest (com.vladmihalcea.hibernate.model.indexlist.Forest)1 Leaf (com.vladmihalcea.hibernate.model.indexlist.Leaf)1 Tree (com.vladmihalcea.hibernate.model.indexlist.Tree)1 Company (com.vladmihalcea.hibernate.model.store.Company)1 Image (com.vladmihalcea.hibernate.model.store.Image)1 Product (com.vladmihalcea.hibernate.model.store.Product)1