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");
}
}
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) {
}
}
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();
}
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());
}
}
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);
}
}
Aggregations