📄 sessionfactoryutils.java
字号:
/**
* Apply the current transaction timeout, if any, to the given
* Hibernate Query object.
* @param query the Hibernate Query object
* @param sessionFactory Hibernate SessionFactory that the Query was created for
*/
public static void applyTransactionTimeout(Query query, SessionFactory sessionFactory) {
SessionHolder sessionHolder = (SessionHolder) TransactionSynchronizationManager.getResource(sessionFactory);
if (sessionHolder != null && sessionHolder.getDeadline() != null) {
query.setTimeout(sessionHolder.getTimeToLiveInSeconds());
}
}
/**
* Apply the current transaction timeout, if any, to the given
* Hibernate Criteria object.
* @param criteria the Hibernate Criteria object
* @param sessionFactory Hibernate SessionFactory that the Criteria was created for
*/
public static void applyTransactionTimeout(Criteria criteria, SessionFactory sessionFactory) {
SessionHolder sessionHolder = (SessionHolder) TransactionSynchronizationManager.getResource(sessionFactory);
if (sessionHolder != null && sessionHolder.getDeadline() != null) {
criteria.setTimeout(sessionHolder.getTimeToLiveInSeconds());
}
}
/**
* Convert the given HibernateException to an appropriate exception from the
* org.springframework.dao hierarchy. Note that it is advisable to handle JDBCException
* specifically by using an SQLExceptionTranslator for the underlying SQLException.
* @param ex HibernateException that occured
* @return the corresponding DataAccessException instance
* @see HibernateAccessor#convertHibernateAccessException
* @see HibernateAccessor#convertJdbcAccessException
* @see HibernateTemplate#execute
*/
public static DataAccessException convertHibernateAccessException(HibernateException ex) {
if (ex instanceof JDBCException) {
// SQLException during Hibernate access: only passed in here from custom code,
// as HibernateTemplate etc will use SQLExceptionTranslator-based handling
return new HibernateJdbcException((JDBCException) ex);
}
if (ex instanceof UnresolvableObjectException) {
return new HibernateObjectRetrievalFailureException((UnresolvableObjectException) ex);
}
if (ex instanceof ObjectNotFoundException) {
return new HibernateObjectRetrievalFailureException((ObjectNotFoundException) ex);
}
if (ex instanceof ObjectDeletedException) {
return new HibernateObjectRetrievalFailureException((ObjectDeletedException) ex);
}
if (ex instanceof WrongClassException) {
return new HibernateObjectRetrievalFailureException((WrongClassException) ex);
}
if (ex instanceof StaleObjectStateException) {
return new HibernateOptimisticLockingFailureException((StaleObjectStateException) ex);
}
if (ex instanceof QueryException) {
return new HibernateQueryException((QueryException) ex);
}
if (ex instanceof PersistentObjectException) {
return new InvalidDataAccessApiUsageException(ex.getMessage());
}
if (ex instanceof TransientObjectException) {
return new InvalidDataAccessApiUsageException(ex.getMessage());
}
// fallback
return new HibernateSystemException(ex);
}
/**
* Close the given Session, created via the given factory,
* if it isn't bound to the thread.
* @param session Session to close
* @param sessionFactory Hibernate SessionFactory that the Session was created with
* @throws DataAccessResourceFailureException if the Session couldn't be closed
*/
public static void closeSessionIfNecessary(Session session, SessionFactory sessionFactory)
throws CleanupFailureDataAccessException {
if (session == null || TransactionSynchronizationManager.hasResource(sessionFactory)) {
return;
}
logger.debug("Closing Hibernate session");
try {
session.close();
}
catch (JDBCException ex) {
// SQLException underneath
throw new CleanupFailureDataAccessException("Could not close Hibernate session", ex.getSQLException());
}
catch (HibernateException ex) {
throw new CleanupFailureDataAccessException("Could not close Hibernate session", ex);
}
}
/**
* Callback for resource cleanup at the end of a Spring-managed JTA transaction,
* i.e. when participating in a JtaTransactionManager transaction.
* @see org.springframework.transaction.jta.JtaTransactionManager
*/
private static class SpringSessionSynchronization implements TransactionSynchronization {
private final SessionHolder sessionHolder;
private final SessionFactory sessionFactory;
private final SQLExceptionTranslator jdbcExceptionTranslator;
private final boolean newSession;
/**
* Whether Hibernate has a looked-up JTA TransactionManager that it will
* automatically register CacheSynchronizations with on Session connect.
*/
private boolean hibernateTransactionCompletion;
private SpringSessionSynchronization(SessionHolder sessionHolder, SessionFactory sessionFactory,
SQLExceptionTranslator jdbcExceptionTranslator, boolean newSession) {
this.sessionHolder = sessionHolder;
this.sessionFactory = sessionFactory;
this.jdbcExceptionTranslator = jdbcExceptionTranslator;
// check whether the SessionFactory has a JTA TransactionManager
this.hibernateTransactionCompletion =
(sessionFactory instanceof SessionFactoryImplementor &&
((SessionFactoryImplementor) sessionFactory).getTransactionManager() != null);
this.newSession = newSession;
}
public void suspend() {
TransactionSynchronizationManager.unbindResource(this.sessionFactory);
}
public void resume() {
TransactionSynchronizationManager.bindResource(this.sessionFactory, this.sessionHolder);
}
public void beforeCommit(boolean readOnly) throws DataAccessException {
if (!readOnly && !this.sessionHolder.getSession().getFlushMode().equals(FlushMode.NEVER)) {
logger.debug("Flushing Hibernate session on transaction synchronization");
try {
this.sessionHolder.getSession().flush();
}
catch (JDBCException ex) {
if (this.jdbcExceptionTranslator != null) {
throw this.jdbcExceptionTranslator.translate("SessionSynchronization", null, ex.getSQLException());
}
else {
throw new HibernateJdbcException(ex);
}
}
catch (HibernateException ex) {
throw convertHibernateAccessException(ex);
}
}
}
public void beforeCompletion() throws CleanupFailureDataAccessException {
if (this.newSession) {
TransactionSynchronizationManager.unbindResource(this.sessionFactory);
if (this.hibernateTransactionCompletion) {
closeSessionIfNecessary(this.sessionHolder.getSession(), this.sessionFactory);
}
}
}
public void afterCompletion(int status) {
if (!this.hibernateTransactionCompletion) {
Session session = this.sessionHolder.getSession();
if (session instanceof SessionImplementor) {
((SessionImplementor) session).afterTransactionCompletion(status == STATUS_COMMITTED);
}
if (this.newSession) {
closeSessionIfNecessary(session, this.sessionFactory);
}
}
this.sessionHolder.setSynchronizedWithTransaction(false);
}
}
/**
* Callback for resource cleanup at the end of a non-Spring JTA transaction,
* i.e. when plain JTA or EJB CMT is used without Spring's JtaTransactionManager.
*/
private static class JtaSessionSynchronization implements Synchronization {
private final SpringSessionSynchronization springSessionSynchronization;
private final TransactionManager jtaTransactionManager;
private JtaSessionSynchronization(SpringSessionSynchronization springSessionSynchronization,
TransactionManager jtaTransactionManager) {
this.springSessionSynchronization = springSessionSynchronization;
this.jtaTransactionManager = jtaTransactionManager;
}
/**
* JTA beforeCompletion callback: just invoked on commit.
* <p>In case of an exception, the JTA transaction gets set to rollback-only.
* (Synchronization.beforeCompletion is not supposed to throw an exception.)
* @see SpringSessionSynchronization#beforeCommit
*/
public void beforeCompletion() {
try {
this.springSessionSynchronization.beforeCommit(false);
}
catch (Throwable ex) {
logger.error("beforeCommit callback threw exception", ex);
try {
this.jtaTransactionManager.setRollbackOnly();
}
catch (SystemException ex2) {
logger.error("Could not set JTA transaction rollback-only", ex2);
}
}
}
/**
* JTA afterCompletion callback: invoked after commit/rollback.
* <p>Needs to invoke SpringSessionSynchronization's beforeCompletion
* at this late stage, as there's no corresponding callback with JTA.
* @see SpringSessionSynchronization#beforeCompletion
* @see SpringSessionSynchronization#afterCompletion
*/
public void afterCompletion(int status) {
// unbind the SessionHolder from the thread
this.springSessionSynchronization.beforeCompletion();
// just reset the synchronizedWithTransaction flag
this.springSessionSynchronization.afterCompletion(-1);
}
}
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -