use of org.hibernate.engine.spi.SessionImplementor in project hibernate-orm by hibernate.
the class SimpleAuditExpression method addToQuery.
@Override
protected void addToQuery(EnversService enversService, AuditReaderImplementor versionsReader, String entityName, String alias, QueryBuilder qb, Parameters parameters) {
String propertyName = CriteriaTools.determinePropertyName(enversService, versionsReader, entityName, propertyNameGetter);
RelationDescription relatedEntity = CriteriaTools.getRelatedEntity(enversService, entityName, propertyName);
if (relatedEntity == null) {
// HHH-9178 - Add support to component type equality.
// This basically will allow = and <> operators to perform component-based equality checks.
// Any other operator for a component type will not be supported.
// Non-component types will continue to behave normally.
final SessionImplementor session = versionsReader.getSessionImplementor();
final Type type = getPropertyType(session, entityName, propertyName);
if (type != null && type.isComponentType()) {
if (!"=".equals(op) && !"<>".equals(op)) {
throw new AuditException("Component-based criterion is not supported for op: " + op);
}
final ComponentType componentType = (ComponentType) type;
for (int i = 0; i < componentType.getPropertyNames().length; i++) {
final Object componentValue = componentType.getPropertyValue(value, i, session);
parameters.addWhereWithParam(alias, propertyName + "_" + componentType.getPropertyNames()[i], op, componentValue);
}
} else {
parameters.addWhereWithParam(alias, propertyName, op, value);
}
} else {
if (!"=".equals(op) && !"<>".equals(op)) {
throw new AuditException("This type of operation: " + op + " (" + entityName + "." + propertyName + ") isn't supported and can't be used in queries.");
}
Object id = relatedEntity.getIdMapper().mapToIdFromEntity(value);
relatedEntity.getIdMapper().addIdEqualsToQuery(parameters, id, alias, null, "=".equals(op));
}
}
use of org.hibernate.engine.spi.SessionImplementor in project hibernate-orm by hibernate.
the class AuditReaderFactory method get.
/**
* Create an audit reader associated with an open session.
*
* @param session An open session.
*
* @return An audit reader associated with the given sesison. It shouldn't be used
* afterQuery the session is closed.
*
* @throws AuditException When the given required listeners aren't installed.
*/
public static AuditReader get(Session session) throws AuditException {
SessionImplementor sessionImpl;
if (!(session instanceof SessionImplementor)) {
sessionImpl = (SessionImplementor) session.getSessionFactory().getCurrentSession();
} else {
sessionImpl = (SessionImplementor) session;
}
final ServiceRegistry serviceRegistry = sessionImpl.getFactory().getServiceRegistry();
final EnversService enversService = serviceRegistry.getService(EnversService.class);
return new AuditReaderImpl(enversService, session, sessionImpl);
}
use of org.hibernate.engine.spi.SessionImplementor in project hibernate-orm by hibernate.
the class AutoDiscoveryTest method testDialectGetColumnAliasExtractor.
@Test
public void testDialectGetColumnAliasExtractor() throws Exception {
Session session = openSession();
final SessionImplementor sessionImplementor = (SessionImplementor) session;
session.beginTransaction();
session.doWork(new Work() {
@Override
public void execute(Connection connection) throws SQLException {
PreparedStatement ps = sessionImplementor.getJdbcCoordinator().getStatementPreparer().prepareStatement(QUERY_STRING);
ResultSet rs = sessionImplementor.getJdbcCoordinator().getResultSetReturn().extract(ps);
try {
ResultSetMetaData metadata = rs.getMetaData();
String column1Alias = getDialect().getColumnAliasExtractor().extractColumnAlias(metadata, 1);
String column2Alias = getDialect().getColumnAliasExtractor().extractColumnAlias(metadata, 2);
Assert.assertFalse("bad dialect.getColumnAliasExtractor impl", column1Alias.equals(column2Alias));
} finally {
sessionImplementor.getJdbcCoordinator().getResourceRegistry().release(rs, ps);
sessionImplementor.getJdbcCoordinator().getResourceRegistry().release(ps);
}
}
});
session.getTransaction().commit();
session.close();
}
use of org.hibernate.engine.spi.SessionImplementor in project hibernate-orm by hibernate.
the class CursorFromCallableTest method testStatementClosing.
@Test
@TestForIssue(jiraKey = "HHH-7984")
public void testStatementClosing() {
Session session = openSession();
session.getTransaction().begin();
// Reading maximum number of opened cursors requires SYS privileges.
// Verify statement closing with JdbcCoordinator#hasRegisteredResources() instead.
// BigDecimal maxCursors = (BigDecimal) session.createSQLQuery( "SELECT value FROM v$parameter WHERE name = 'open_cursors'" ).uniqueResult();
// for ( int i = 0; i < maxCursors + 10; ++i ) { named_query_execution }
Assert.assertEquals(Arrays.asList(new NumValue(1, "Line 1"), new NumValue(2, "Line 2")), session.getNamedQuery("NumValue.getSomeValues").list());
JdbcCoordinator jdbcCoordinator = ((SessionImplementor) session).getJdbcCoordinator();
Assert.assertFalse("Prepared statement and result set should be released afterQuery query execution.", jdbcCoordinator.getResourceRegistry().hasRegisteredResources());
session.getTransaction().commit();
session.close();
}
use of org.hibernate.engine.spi.SessionImplementor in project spring-framework by spring-projects.
the class HibernateTransactionManager method doBegin.
@Override
@SuppressWarnings("deprecation")
protected void doBegin(Object transaction, TransactionDefinition definition) {
HibernateTransactionObject txObject = (HibernateTransactionObject) transaction;
if (txObject.hasConnectionHolder() && !txObject.getConnectionHolder().isSynchronizedWithTransaction()) {
throw new IllegalTransactionStateException("Pre-bound JDBC Connection found! HibernateTransactionManager does not support " + "running within DataSourceTransactionManager if told to manage the DataSource itself. " + "It is recommended to use a single HibernateTransactionManager for all transactions " + "on a single DataSource, no matter whether Hibernate or JDBC access.");
}
Session session = null;
try {
if (txObject.getSessionHolder() == null || txObject.getSessionHolder().isSynchronizedWithTransaction()) {
Interceptor entityInterceptor = getEntityInterceptor();
Session newSession = (entityInterceptor != null ? getSessionFactory().withOptions().interceptor(entityInterceptor).openSession() : getSessionFactory().openSession());
if (logger.isDebugEnabled()) {
logger.debug("Opened new Session [" + newSession + "] for Hibernate transaction");
}
txObject.setSession(newSession);
}
session = txObject.getSessionHolder().getSession();
if (this.prepareConnection && isSameConnectionForEntireSession(session)) {
// We're allowed to change the transaction settings of the JDBC Connection.
if (logger.isDebugEnabled()) {
logger.debug("Preparing JDBC Connection of Hibernate Session [" + session + "]");
}
Connection con = ((SessionImplementor) session).connection();
Integer previousIsolationLevel = DataSourceUtils.prepareConnectionForTransaction(con, definition);
txObject.setPreviousIsolationLevel(previousIsolationLevel);
if (this.allowResultAccessAfterCompletion && !txObject.isNewSession()) {
int currentHoldability = con.getHoldability();
if (currentHoldability != ResultSet.HOLD_CURSORS_OVER_COMMIT) {
txObject.setPreviousHoldability(currentHoldability);
con.setHoldability(ResultSet.HOLD_CURSORS_OVER_COMMIT);
}
}
} else {
// Not allowed to change the transaction settings of the JDBC Connection.
if (definition.getIsolationLevel() != TransactionDefinition.ISOLATION_DEFAULT) {
// We should set a specific isolation level but are not allowed to...
throw new InvalidIsolationLevelException("HibernateTransactionManager is not allowed to support custom isolation levels: " + "make sure that its 'prepareConnection' flag is on (the default) and that the " + "Hibernate connection release mode is set to 'on_close' (the default for JDBC).");
}
if (logger.isDebugEnabled()) {
logger.debug("Not preparing JDBC Connection of Hibernate Session [" + session + "]");
}
}
if (definition.isReadOnly() && txObject.isNewSession()) {
// Just set to MANUAL in case of a new Session for this transaction.
session.setFlushMode(FlushMode.MANUAL);
}
if (!definition.isReadOnly() && !txObject.isNewSession()) {
// We need AUTO or COMMIT for a non-read-only transaction.
FlushMode flushMode = SessionFactoryUtils.getFlushMode(session);
if (FlushMode.MANUAL.equals(flushMode)) {
session.setFlushMode(FlushMode.AUTO);
txObject.getSessionHolder().setPreviousFlushMode(flushMode);
}
}
Transaction hibTx;
// Register transaction timeout.
int timeout = determineTimeout(definition);
if (timeout != TransactionDefinition.TIMEOUT_DEFAULT) {
// Use Hibernate's own transaction timeout mechanism on Hibernate 3.1+
// Applies to all statements, also to inserts, updates and deletes!
hibTx = session.getTransaction();
hibTx.setTimeout(timeout);
hibTx.begin();
} else {
// Open a plain Hibernate transaction without specified timeout.
hibTx = session.beginTransaction();
}
// Add the Hibernate transaction to the session holder.
txObject.getSessionHolder().setTransaction(hibTx);
// Register the Hibernate Session's JDBC Connection for the DataSource, if set.
if (getDataSource() != null) {
Connection con = ((SessionImplementor) session).connection();
ConnectionHolder conHolder = new ConnectionHolder(con);
if (timeout != TransactionDefinition.TIMEOUT_DEFAULT) {
conHolder.setTimeoutInSeconds(timeout);
}
if (logger.isDebugEnabled()) {
logger.debug("Exposing Hibernate transaction as JDBC transaction [" + con + "]");
}
TransactionSynchronizationManager.bindResource(getDataSource(), conHolder);
txObject.setConnectionHolder(conHolder);
}
// Bind the session holder to the thread.
if (txObject.isNewSessionHolder()) {
TransactionSynchronizationManager.bindResource(getSessionFactory(), txObject.getSessionHolder());
}
txObject.getSessionHolder().setSynchronizedWithTransaction(true);
} catch (Throwable ex) {
if (txObject.isNewSession()) {
try {
if (session.getTransaction().getStatus() == TransactionStatus.ACTIVE) {
session.getTransaction().rollback();
}
} catch (Throwable ex2) {
logger.debug("Could not rollback Session after failed transaction begin", ex);
} finally {
SessionFactoryUtils.closeSession(session);
txObject.setSessionHolder(null);
}
}
throw new CannotCreateTransactionException("Could not open Hibernate Session for transaction", ex);
}
}
Aggregations