use of org.hibernate.engine.spi.PersistenceContext in project hibernate-orm by hibernate.
the class TestAutoFlushBeforeQueryExecution method testAutoflushIsNotRequiredWithUnrelatedCollectionChange.
@Test
public void testAutoflushIsNotRequiredWithUnrelatedCollectionChange() {
Session s = openSession();
Transaction txn = s.beginTransaction();
Publisher publisher = new Publisher();
publisher.setName("name");
s.save(publisher);
assertTrue("autoflush entity create", s.createQuery("from Publisher p").list().size() == 1);
publisher.setName("name");
assertTrue("autoflush entity update", s.createQuery("from Publisher p where p.name='name'").list().size() == 1);
UnrelatedEntity unrelatedEntity = new UnrelatedEntity();
s.save(unrelatedEntity);
txn.commit();
s.close();
s = openSession();
txn = s.beginTransaction();
unrelatedEntity = (UnrelatedEntity) s.get(UnrelatedEntity.class, unrelatedEntity.getId());
publisher = (Publisher) s.get(Publisher.class, publisher.getId());
assertTrue(publisher.getAuthors().isEmpty());
final PersistenceContext persistenceContext = ((SessionImplementor) s).getPersistenceContext();
final ActionQueue actionQueue = ((SessionImpl) s).getActionQueue();
assertEquals(1, persistenceContext.getCollectionEntries().size());
assertEquals(1, persistenceContext.getCollectionsByKey().size());
assertTrue(persistenceContext.getCollectionEntries().containsKey(publisher.getAuthors()));
assertTrue(persistenceContext.getCollectionsByKey().values().contains(publisher.getAuthors()));
assertEquals(0, actionQueue.numberOfCollectionRemovals());
Author author1 = new Author();
author1.setPublisher(publisher);
publisher.getAuthors().add(author1);
assertTrue(s.createQuery("from UnrelatedEntity").list().size() == 1);
assertEquals(2, persistenceContext.getCollectionEntries().size());
assertEquals(1, persistenceContext.getCollectionsByKey().size());
assertTrue(persistenceContext.getCollectionEntries().containsKey(publisher.getAuthors()));
assertTrue(persistenceContext.getCollectionEntries().containsKey(author1.getBooks()));
assertTrue(persistenceContext.getCollectionsByKey().values().contains(publisher.getAuthors()));
assertEquals(0, actionQueue.numberOfCollectionRemovals());
author1.setPublisher(null);
s.delete(author1);
publisher.getAuthors().clear();
assertEquals(0, actionQueue.numberOfCollectionRemovals());
assertTrue(s.createQuery("from UnrelatedEntity").list().size() == 1);
assertEquals(2, persistenceContext.getCollectionEntries().size());
assertEquals(1, persistenceContext.getCollectionsByKey().size());
assertTrue(persistenceContext.getCollectionEntries().containsKey(publisher.getAuthors()));
assertTrue(persistenceContext.getCollectionEntries().containsKey(author1.getBooks()));
assertTrue(persistenceContext.getCollectionsByKey().values().contains(publisher.getAuthors()));
assertEquals(0, actionQueue.numberOfCollectionRemovals());
Set<Author> authorsOld = publisher.getAuthors();
publisher.setAuthors(new HashSet<Author>());
Author author2 = new Author();
author2.setName("author2");
author2.setPublisher(publisher);
publisher.getAuthors().add(author2);
List results = s.createQuery("from UnrelatedEntity").list();
assertEquals(1, results.size());
assertEquals(4, persistenceContext.getCollectionEntries().size());
assertEquals(1, persistenceContext.getCollectionsByKey().size());
assertTrue(persistenceContext.getCollectionEntries().containsKey(publisher.getAuthors()));
assertTrue(persistenceContext.getCollectionEntries().containsKey(author2.getBooks()));
assertTrue(persistenceContext.getCollectionEntries().containsKey(authorsOld));
assertTrue(persistenceContext.getCollectionEntries().containsKey(author1.getBooks()));
assertTrue(persistenceContext.getCollectionsByKey().values().contains(authorsOld));
assertEquals(0, actionQueue.numberOfCollectionRemovals());
s.flush();
assertEquals(2, persistenceContext.getCollectionEntries().size());
assertEquals(2, persistenceContext.getCollectionsByKey().size());
assertTrue(persistenceContext.getCollectionEntries().containsKey(publisher.getAuthors()));
assertTrue(persistenceContext.getCollectionEntries().containsKey(author2.getBooks()));
assertTrue(persistenceContext.getCollectionsByKey().values().contains(publisher.getAuthors()));
assertTrue(persistenceContext.getCollectionsByKey().values().contains(author2.getBooks()));
assertEquals(0, actionQueue.numberOfCollectionRemovals());
s.delete(publisher);
assertTrue("autoflush delete", s.createQuery("from UnrelatedEntity").list().size() == 1);
s.delete(unrelatedEntity);
txn.commit();
s.close();
}
use of org.hibernate.engine.spi.PersistenceContext in project hibernate-orm by hibernate.
the class EvictAuditDataAfterCommitTest method checkEmptyAuditSessionCache.
private void checkEmptyAuditSessionCache(Session session, String... auditEntityNames) {
List<String> entityNames = Arrays.asList(auditEntityNames);
PersistenceContext persistenceContext = ((SessionImplementor) session).getPersistenceContext();
for (Map.Entry<Object, EntityEntry> entrySet : persistenceContext.reentrantSafeEntityEntries()) {
final EntityEntry entityEntry = entrySet.getValue();
if (entityNames.contains(entityEntry.getEntityName())) {
assert false : "Audit data shall not be stored in the session level cache. This causes performance issues.";
}
Assert.assertFalse("Revision entity shall not be stored in the session level cache. This causes performance issues.", SequenceIdRevisionEntity.class.getName().equals(entityEntry.getEntityName()));
}
}
use of org.hibernate.engine.spi.PersistenceContext in project hibernate-orm by hibernate.
the class AbstractFlushingEventListener method flushEverythingToExecutions.
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
// Pre-flushing section
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
/**
* Coordinates the processing necessary to get things ready for executions
* as db calls by preping the session caches and moving the appropriate
* entities and collections to their respective execution queues.
*
* @param event The flush event.
* @throws HibernateException Error flushing caches to execution queues.
*/
protected void flushEverythingToExecutions(FlushEvent event) throws HibernateException {
LOG.trace("Flushing session");
EventSource session = event.getSession();
final PersistenceContext persistenceContext = session.getPersistenceContext();
session.getInterceptor().preFlush(new LazyIterator(persistenceContext.getEntitiesByKey()));
prepareEntityFlushes(session, persistenceContext);
// we could move this inside if we wanted to
// tolerate collection initializations during
// collection dirty checking:
prepareCollectionFlushes(persistenceContext);
// now, any collections that are initialized
// inside this block do not get updated - they
// are ignored until the next flush
persistenceContext.setFlushing(true);
try {
int entityCount = flushEntities(event, persistenceContext);
int collectionCount = flushCollections(session, persistenceContext);
event.setNumberOfEntitiesProcessed(entityCount);
event.setNumberOfCollectionsProcessed(collectionCount);
} finally {
persistenceContext.setFlushing(false);
}
//some statistics
logFlushResults(event);
}
use of org.hibernate.engine.spi.PersistenceContext in project hibernate-orm by hibernate.
the class DefaultLoadEventListener method convertCacheEntryToEntity.
private Object convertCacheEntryToEntity(CacheEntry entry, Serializable entityId, EntityPersister persister, LoadEvent event, EntityKey entityKey) {
final EventSource session = event.getSession();
final SessionFactoryImplementor factory = session.getFactory();
final EntityPersister subclassPersister;
if (traceEnabled) {
LOG.tracef("Converting second-level cache entry [%s] into entity : %s", entry, MessageHelper.infoString(persister, entityId, factory));
}
final Object entity;
subclassPersister = factory.getEntityPersister(entry.getSubclass());
final Object optionalObject = event.getInstanceToLoad();
entity = optionalObject == null ? session.instantiate(subclassPersister, entityId) : optionalObject;
// make it circular-reference safe
TwoPhaseLoad.addUninitializedCachedEntity(entityKey, entity, subclassPersister, LockMode.NONE, entry.getVersion(), session);
final PersistenceContext persistenceContext = session.getPersistenceContext();
final Object[] values;
final Object version;
final boolean isReadOnly;
final Type[] types = subclassPersister.getPropertyTypes();
// initializes the entity by (desired) side-effect
values = ((StandardCacheEntryImpl) entry).assemble(entity, entityId, subclassPersister, session.getInterceptor(), session);
if (((StandardCacheEntryImpl) entry).isDeepCopyNeeded()) {
TypeHelper.deepCopy(values, types, subclassPersister.getPropertyUpdateability(), values, session);
}
version = Versioning.getVersion(values, subclassPersister);
LOG.tracef("Cached Version : %s", version);
final Object proxy = persistenceContext.getProxy(entityKey);
if (proxy != null) {
// there is already a proxy for this impl
// only set the status to read-only if the proxy is read-only
isReadOnly = ((HibernateProxy) proxy).getHibernateLazyInitializer().isReadOnly();
} else {
isReadOnly = session.isDefaultReadOnly();
}
persistenceContext.addEntry(entity, (isReadOnly ? Status.READ_ONLY : Status.MANAGED), values, null, entityId, version, LockMode.NONE, true, subclassPersister, false);
subclassPersister.afterInitialize(entity, session);
persistenceContext.initializeNonLazyCollections();
//PostLoad is needed for EJB3
PostLoadEvent postLoadEvent = event.getPostLoadEvent().setEntity(entity).setId(entityId).setPersister(persister);
for (PostLoadEventListener listener : postLoadEventListeners(session)) {
listener.onPostLoad(postLoadEvent);
}
return entity;
}
use of org.hibernate.engine.spi.PersistenceContext in project hibernate-orm by hibernate.
the class AbstractFlushingEventListener method logFlushResults.
@SuppressWarnings(value = { "unchecked" })
private void logFlushResults(FlushEvent event) {
if (!LOG.isDebugEnabled()) {
return;
}
final EventSource session = event.getSession();
final PersistenceContext persistenceContext = session.getPersistenceContext();
LOG.debugf("Flushed: %s insertions, %s updates, %s deletions to %s objects", session.getActionQueue().numberOfInsertions(), session.getActionQueue().numberOfUpdates(), session.getActionQueue().numberOfDeletions(), persistenceContext.getNumberOfManagedEntities());
LOG.debugf("Flushed: %s (re)creations, %s updates, %s removals to %s collections", session.getActionQueue().numberOfCollectionCreations(), session.getActionQueue().numberOfCollectionUpdates(), session.getActionQueue().numberOfCollectionRemovals(), persistenceContext.getCollectionEntries().size());
new EntityPrinter(session.getFactory()).toString(persistenceContext.getEntitiesByKey().entrySet());
}
Aggregations