use of org.hibernate.engine.spi.SessionImplementor in project hibernate-orm by hibernate.
the class DynamicFilterTest method testSecondLevelCachedCollectionsFiltering.
@Test
public void testSecondLevelCachedCollectionsFiltering() {
TestData testData = new TestData();
testData.prepare();
Session session = openSession();
long ts = ((SessionImplementor) session).getTimestamp();
// Force a collection into the second level cache, with its non-filtered elements
Salesperson sp = (Salesperson) session.load(Salesperson.class, testData.steveId);
Hibernate.initialize(sp.getOrders());
CollectionPersister persister = sessionFactory().getCollectionPersister(Salesperson.class.getName() + ".orders");
assertTrue("No cache for collection", persister.hasCache());
CollectionRegionAccessStrategy cache = persister.getCacheAccessStrategy();
Object cacheKey = cache.generateCacheKey(testData.steveId, persister, sessionFactory(), session.getTenantIdentifier());
CollectionCacheEntry cachedData = (CollectionCacheEntry) cache.get((SessionImplementor) session, cacheKey, ts);
assertNotNull("collection was not in cache", cachedData);
session.close();
session = openSession();
ts = ((SessionImplementor) session).getTimestamp();
session.enableFilter("fulfilledOrders").setParameter("asOfDate", testData.lastMonth.getTime());
sp = (Salesperson) session.createQuery("from Salesperson as s where s.id = :id").setLong("id", testData.steveId).uniqueResult();
assertEquals("Filtered-collection not bypassing 2L-cache", 1, sp.getOrders().size());
Object cacheKey2 = cache.generateCacheKey(testData.steveId, persister, sessionFactory(), session.getTenantIdentifier());
CollectionCacheEntry cachedData2 = (CollectionCacheEntry) persister.getCacheAccessStrategy().get((SessionImplementor) session, cacheKey2, ts);
assertNotNull("collection no longer in cache!", cachedData2);
assertSame("Different cache values!", cachedData, cachedData2);
session.close();
session = openSession();
session.enableFilter("fulfilledOrders").setParameter("asOfDate", testData.lastMonth.getTime());
sp = (Salesperson) session.load(Salesperson.class, testData.steveId);
assertEquals("Filtered-collection not bypassing 2L-cache", 1, sp.getOrders().size());
session.close();
// Finally, make sure that the original cached version did not get over-written
session = openSession();
sp = (Salesperson) session.load(Salesperson.class, testData.steveId);
assertEquals("Actual cached version got over-written", 2, sp.getOrders().size());
session.close();
testData.release();
}
use of org.hibernate.engine.spi.SessionImplementor in project hibernate-orm by hibernate.
the class TestAutoFlushBeforeQueryExecution method testAutoflushIsRequired.
@Test
public void testAutoflushIsRequired() {
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);
txn.commit();
s.close();
s = openSession();
txn = s.beginTransaction();
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("autoflush collection update", s.createQuery("select a from Publisher p join p.authors a").list().size() == 1);
assertEquals(2, persistenceContext.getCollectionEntries().size());
assertEquals(2, persistenceContext.getCollectionsByKey().size());
assertTrue(persistenceContext.getCollectionEntries().containsKey(publisher.getAuthors()));
assertTrue(persistenceContext.getCollectionEntries().containsKey(author1.getBooks()));
assertTrue(persistenceContext.getCollectionsByKey().values().contains(publisher.getAuthors()));
assertTrue(persistenceContext.getCollectionsByKey().values().contains(author1.getBooks()));
assertEquals(0, actionQueue.numberOfCollectionRemovals());
author1.setPublisher(null);
s.delete(author1);
publisher.getAuthors().clear();
assertEquals(0, actionQueue.numberOfCollectionRemovals());
assertTrue("autoflush collection update", s.createQuery("select a from Publisher p join p.authors a").list().size() == 0);
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());
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("select a from Publisher p join p.authors a").list();
assertEquals(1, results.size());
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 Publisher p").list().size() == 0);
txn.commit();
s.close();
}
use of org.hibernate.engine.spi.SessionImplementor in project hibernate-orm by hibernate.
the class ResourceLocalTransactionJoiningTest method testExpectations.
@Test
@TestForIssue(jiraKey = "HHH-9859")
public void testExpectations() {
// JPA spec is very vague on what should happen here. It does vaguely
// imply that javax.persistence.EntityManager.joinTransaction() should only be used
// for JTA EMs, however it does not enforced that nor does the TCK check that.
// And the TCK in fact does test calls to javax.persistence.EntityManager.isJoinedToTransaction()
// from resource-local EMs, so lets make sure those work..
Session session = sessionFactory().openSession();
JdbcResourceLocalTransactionCoordinatorImpl tc = ExtraAssertions.assertTyping(JdbcResourceLocalTransactionCoordinatorImpl.class, ((SessionImplementor) session).getTransactionCoordinator());
assertFalse(tc.isJoined());
session.beginTransaction();
tc = ExtraAssertions.assertTyping(JdbcResourceLocalTransactionCoordinatorImpl.class, ((SessionImplementor) session).getTransactionCoordinator());
assertTrue(tc.isJoined());
session.getTransaction().rollback();
session.close();
}
use of org.hibernate.engine.spi.SessionImplementor in project hibernate-orm by hibernate.
the class CacheLazyLoadNoTransTest method isCached.
private boolean isCached(Serializable id, Class<?> entityClass, String attr) {
Session session = openSession();
CollectionPersister persister = sessionFactory().getCollectionPersister(entityClass.getName() + "." + attr);
CollectionRegionAccessStrategy cache = persister.getCacheAccessStrategy();
Object key = cache.generateCacheKey(id, persister, sessionFactory(), session.getTenantIdentifier());
Object cachedValue = cache.get(((SessionImplementor) session), key, ((SessionImplementor) session).getTimestamp());
session.close();
return cachedValue != null;
}
use of org.hibernate.engine.spi.SessionImplementor in project hibernate-orm by hibernate.
the class DefaultPersistEventListener method onPersist.
/**
* Handle the given create event.
*
* @param event The create event to be handled.
*
* @throws HibernateException
*/
public void onPersist(PersistEvent event, Map createCache) throws HibernateException {
final SessionImplementor source = event.getSession();
final Object object = event.getObject();
final Object entity;
if (object instanceof HibernateProxy) {
LazyInitializer li = ((HibernateProxy) object).getHibernateLazyInitializer();
if (li.isUninitialized()) {
if (li.getSession() == source) {
//NOTE EARLY EXIT!
return;
} else {
throw new PersistentObjectException("uninitialized proxy passed to persist()");
}
}
entity = li.getImplementation();
} else {
entity = object;
}
final String entityName;
if (event.getEntityName() != null) {
entityName = event.getEntityName();
} else {
entityName = source.bestGuessEntityName(entity);
event.setEntityName(entityName);
}
final EntityEntry entityEntry = source.getPersistenceContext().getEntry(entity);
EntityState entityState = getEntityState(entity, entityName, entityEntry, source);
if (entityState == EntityState.DETACHED) {
// JPA 2, in its version of a "foreign generated", allows the id attribute value
// to be manually set by the user, even though this manual value is irrelevant.
// The issue is that this causes problems with the Hibernate unsaved-value strategy
// which comes into play here in determining detached/transient state.
//
// Detect if we have this situation and if so null out the id value and calculate the
// entity state again.
// NOTE: entityEntry must be null to get here, so we cannot use any of its values
EntityPersister persister = source.getFactory().getEntityPersister(entityName);
if (ForeignGenerator.class.isInstance(persister.getIdentifierGenerator())) {
if (LOG.isDebugEnabled() && persister.getIdentifier(entity, source) != null) {
LOG.debug("Resetting entity id attribute to null for foreign generator");
}
persister.setIdentifier(entity, null, source);
entityState = getEntityState(entity, entityName, entityEntry, source);
}
}
switch(entityState) {
case DETACHED:
{
throw new PersistentObjectException("detached entity passed to persist: " + getLoggableName(event.getEntityName(), entity));
}
case PERSISTENT:
{
entityIsPersistent(event, createCache);
break;
}
case TRANSIENT:
{
entityIsTransient(event, createCache);
break;
}
case DELETED:
{
entityEntry.setStatus(Status.MANAGED);
entityEntry.setDeletedState(null);
event.getSession().getActionQueue().unScheduleDeletion(entityEntry, event.getObject());
entityIsDeleted(event, createCache);
break;
}
default:
{
throw new ObjectDeletedException("deleted entity passed to persist", null, getLoggableName(event.getEntityName(), entity));
}
}
}
Aggregations