use of org.hibernate.internal.SessionImpl in project candlepin by candlepin.
the class AbstractHibernateCurator method lockAndLoadById.
/**
* Loads an entity with a pessimistic lock using the specified entity class and ID. If the
* entity has already been loaded, it will be refreshed with the lock instead. If a matching
* entity could not be found, this method returns null.
*
* @param entityClass
* The class representing the type of entity to fetch (i.e. Pool.class or Product.class)
*
* @param id
* The id of the entity to load/refresh and lock
*
* @return
* A locked entity instance, or null if a matching entity could not be found
*/
@SuppressWarnings("unchecked")
protected E lockAndLoadById(Class<E> entityClass, Serializable id) {
EntityManager entityManager = this.getEntityManager();
SessionImpl session = (SessionImpl) this.currentSession();
ClassMetadata metadata = session.getFactory().getClassMetadata(entityClass);
// and check if it's already in the session cache without doing a database lookup
if (metadata == null || !metadata.hasIdentifierProperty()) {
throw new UnsupportedOperationException("lockAndLoad only supports entities with database identifiers");
}
// Fetch the entity persister and session context so we can check the session cache for an
// entity before hitting the database.
EntityPersister persister = session.getFactory().getEntityPersister(metadata.getEntityName());
PersistenceContext context = session.getPersistenceContext();
// Lookup whether or not we have an entity with a given ID in the current session's cache.
// See the notes in lockAndLoadByIds for details as to why we're going about it this way.
EntityKey key = session.generateEntityKey(id, persister);
E entity = (E) context.getEntity(key);
if (entity == null) {
// The entity isn't in the local session, we'll need to query for it
String idName = metadata.getIdentifierPropertyName();
if (idName == null) {
// This shouldn't happen.
throw new RuntimeException("Unable to fetch identifier property name");
}
// Impl note:
// We're building the query here using JPA Criteria to avoid fiddling with string
// building and, potentially, erroneously using the class name as the entity name.
// Additionally, using a query (as opposed to the .find and .load methods) lets us set
// the flush, cache and lock modes for the entity we're attempting to fetch.
CriteriaBuilder builder = entityManager.getCriteriaBuilder();
CriteriaQuery<E> query = builder.createQuery(entityClass);
Root<E> root = query.from(entityClass);
Path<Serializable> target = root.<Serializable>get(idName);
ParameterExpression<Serializable> param = builder.parameter(Serializable.class);
query.select(root).where(builder.equal(target, param));
// by Hibernate down to a CacheMode.REFRESH.
try {
entity = entityManager.createQuery(query).setFlushMode(FlushModeType.COMMIT).setHint(AvailableSettings.SHARED_CACHE_RETRIEVE_MODE, CacheRetrieveMode.BYPASS).setHint(AvailableSettings.SHARED_CACHE_STORE_MODE, CacheStoreMode.REFRESH).setLockMode(LockModeType.PESSIMISTIC_WRITE).setParameter(param, id).getSingleResult();
} catch (NoResultException exception) {
// No entity found matching the ID. We don't define this as an error case, so we're
// going to silently discard the exception.
}
} else {
// It's already available locally. Issue a refresh with a lock.
entityManager.refresh(entity, LockModeType.PESSIMISTIC_WRITE);
}
return entity;
}
use of org.hibernate.internal.SessionImpl in project hibernate-orm by hibernate.
the class ProxyTest method testFullyLoadedPCSerialization.
@Test
public void testFullyLoadedPCSerialization() {
Session s = openSession();
Transaction t = s.beginTransaction();
Long lastContainerId = null;
int containerCount = 10;
int nestedDataPointCount = 5;
for (int c_indx = 0; c_indx < containerCount; c_indx++) {
Owner owner = new Owner("Owner #" + c_indx);
Container container = new Container("Container #" + c_indx);
container.setOwner(owner);
for (int dp_indx = 0; dp_indx < nestedDataPointCount; dp_indx++) {
DataPoint dp = new DataPoint();
dp.setDescription("data-point [" + c_indx + ", " + dp_indx + "]");
// more HSQLDB fun...
// dp.setX( new BigDecimal( c_indx ) );
dp.setX(new BigDecimal(c_indx + dp_indx));
dp.setY(new BigDecimal(dp_indx));
container.getDataPoints().add(dp);
}
s.save(container);
lastContainerId = container.getId();
}
t.commit();
s.close();
s = openSession();
s.setFlushMode(FlushMode.MANUAL);
t = s.beginTransaction();
// load the last container as a proxy
Container proxy = (Container) s.load(Container.class, lastContainerId);
assertFalse(Hibernate.isInitialized(proxy));
// load the rest back into the PC
List all = s.createQuery("from Container as c inner join fetch c.owner inner join fetch c.dataPoints where c.id <> :last").setLong("last", lastContainerId.longValue()).list();
Container container = (Container) all.get(0);
s.delete(container);
// force a snapshot retrieval of the proxied container
SessionImpl sImpl = (SessionImpl) s;
sImpl.getPersistenceContext().getDatabaseSnapshot(lastContainerId, sImpl.getFactory().getEntityPersister(Container.class.getName()));
assertFalse(Hibernate.isInitialized(proxy));
t.commit();
// int iterations = 50;
// long cumulativeTime = 0;
// long cumulativeSize = 0;
// for ( int i = 0; i < iterations; i++ ) {
// final long start = System.currentTimeMillis();
// byte[] bytes = SerializationHelper.serialize( s );
// SerializationHelper.deserialize( bytes );
// final long end = System.currentTimeMillis();
// cumulativeTime += ( end - start );
// int size = bytes.length;
// cumulativeSize += size;
// // System.out.println( "Iteration #" + i + " took " + ( end - start ) + " ms : size = " + size + " bytes" );
// }
// System.out.println( "Average time : " + ( cumulativeTime / iterations ) + " ms" );
// System.out.println( "Average size : " + ( cumulativeSize / iterations ) + " bytes" );
byte[] bytes = SerializationHelper.serialize(s);
SerializationHelper.deserialize(bytes);
t = s.beginTransaction();
int count = s.createQuery("delete DataPoint").executeUpdate();
assertEquals("unexpected DP delete count", (containerCount * nestedDataPointCount), count);
count = s.createQuery("delete Container").executeUpdate();
assertEquals("unexpected container delete count", containerCount, count);
count = s.createQuery("delete Owner").executeUpdate();
assertEquals("unexpected owner delete count", containerCount, count);
t.commit();
s.close();
}
use of org.hibernate.internal.SessionImpl in project hibernate-orm by hibernate.
the class TypeTest method runBasicTests.
protected <T> void runBasicTests(AbstractSingleColumnStandardBasicType<T> type, T original, T copy, T different) {
// Not really used
final SessionImpl session = null;
final boolean nonCopyable = Class.class.isInstance(original) || Currency.class.isInstance(original);
if (!nonCopyable) {
// these checks exclude classes which cannot really be cloned (singetons/enums)
assertFalse(original == copy);
}
assertTrue(original == type.replace(original, copy, null, null, null));
// following tests assert that types work with properties not yet loaded in bytecode enhanced entities
assertSame(copy, type.replace(LazyPropertyInitializer.UNFETCHED_PROPERTY, copy, null, null, null));
assertNotEquals(LazyPropertyInitializer.UNFETCHED_PROPERTY, type.replace(original, LazyPropertyInitializer.UNFETCHED_PROPERTY, null, null, null));
assertTrue(type.isSame(original, copy));
assertTrue(type.isEqual(original, copy));
assertTrue(type.isEqual(original, copy));
assertTrue(type.isEqual(original, copy, null));
assertFalse(type.isSame(original, different));
assertFalse(type.isEqual(original, different));
assertFalse(type.isEqual(original, different));
assertFalse(type.isEqual(original, different, null));
assertFalse(type.isDirty(original, copy, session));
assertFalse(type.isDirty(original, copy, ArrayHelper.FALSE, session));
assertFalse(type.isDirty(original, copy, ArrayHelper.TRUE, session));
assertTrue(type.isDirty(original, different, session));
assertFalse(type.isDirty(original, different, ArrayHelper.FALSE, session));
assertTrue(type.isDirty(original, different, ArrayHelper.TRUE, session));
assertFalse(type.isModified(original, copy, ArrayHelper.FALSE, session));
assertFalse(type.isModified(original, copy, ArrayHelper.TRUE, session));
assertTrue(type.isModified(original, different, ArrayHelper.FALSE, session));
assertTrue(type.isModified(original, different, ArrayHelper.TRUE, session));
}
use of org.hibernate.internal.SessionImpl in project evosuite by EvoSuite.
the class DBManagerIntTest method testTableInitialization.
@Test
public void testTableInitialization() throws SQLException {
Connection c = ((SessionImpl) DBManager.getInstance().getCurrentEntityManager().getDelegate()).connection();
Statement s = c.createStatement();
Set<String> tables = new LinkedHashSet<>();
ResultSet rs = s.executeQuery("select table_name " + "from INFORMATION_SCHEMA.system_tables " + "where table_type='TABLE' and table_schem='PUBLIC'");
while (rs.next()) {
if (!rs.getString(1).startsWith("DUAL_")) {
tables.add(rs.getString(1));
}
}
rs.close();
s.close();
Assert.assertTrue(tables.contains("KVPair_table".toUpperCase()));
}
use of org.hibernate.internal.SessionImpl in project evosuite by EvoSuite.
the class DBManagerIntTest method testDirectSQLInsertFollowedByClear.
@Test
public void testDirectSQLInsertFollowedByClear() throws SQLException {
String tableName = "KVPair_table";
Connection c = ((SessionImpl) DBManager.getInstance().getCurrentEntityManager().getDelegate()).connection();
Statement s = c.createStatement();
ResultSet rs = null;
s.executeUpdate("INSERT INTO KVPair_table VALUES 'a', 'b'");
rs = s.executeQuery("SELECT * from " + tableName);
Assert.assertTrue(rs.next());
rs.close();
s.close();
DBManager.getInstance().clearDatabase();
s = c.createStatement();
rs = s.executeQuery("SELECT * from " + tableName);
// no data
Assert.assertFalse(rs.next());
rs.close();
s.close();
}
Aggregations