package org.springframework.orm.hibernate5;
import org.hibernate.FlushMode;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.core.Ordered;
import org.springframework.dao.DataAccessException;
import org.springframework.transaction.support.TransactionSynchronization;
import org.springframework.transaction.support.TransactionSynchronizationManager;
public class SpringSessionSynchronization implements TransactionSynchronization, Ordered {
private final SessionHolder sessionHolder;
private final SessionFactory sessionFactory;
private final boolean newSession;
private boolean holderActive = true;
public SpringSessionSynchronization(SessionHolder sessionHolder, SessionFactory sessionFactory) {
this(sessionHolder, sessionFactory, false);
}
public SpringSessionSynchronization(SessionHolder sessionHolder, SessionFactory sessionFactory, boolean newSession) {
this.sessionHolder = sessionHolder;
this.sessionFactory = sessionFactory;
this.newSession = newSession;
}
private Session getCurrentSession() {
return this.sessionHolder.getSession();
}
@Override
public int getOrder() {
return SessionFactoryUtils.SESSION_SYNCHRONIZATION_ORDER;
}
@Override
public void suspend() {
if (this.holderActive) {
TransactionSynchronizationManager.unbindResource(this.sessionFactory);
getCurrentSession().disconnect();
}
}
@Override
public void resume() {
if (this.holderActive) {
TransactionSynchronizationManager.bindResource(this.sessionFactory, this.sessionHolder);
}
}
@Override
public void flush() {
SessionFactoryUtils.flush(getCurrentSession(), false);
}
@Override
public void beforeCommit(boolean readOnly) throws DataAccessException {
if (!readOnly) {
Session session = getCurrentSession();
if (!FlushMode.MANUAL.equals(session.getHibernateFlushMode())) {
SessionFactoryUtils.flush(getCurrentSession(), true);
}
}
}
@Override
public void beforeCompletion() {
try {
Session session = this.sessionHolder.getSession();
if (this.sessionHolder.getPreviousFlushMode() != null) {
session.setHibernateFlushMode(this.sessionHolder.getPreviousFlushMode());
}
session.disconnect();
}
finally {
if (this.newSession) {
TransactionSynchronizationManager.unbindResource(this.sessionFactory);
this.holderActive = false;
}
}
}
@Override
public void afterCommit() {
}
@Override
public void afterCompletion(int status) {
try {
if (status != STATUS_COMMITTED) {
this.sessionHolder.getSession().clear();
}
}
finally {
this.sessionHolder.setSynchronizedWithTransaction(false);
if (this.newSession) {
SessionFactoryUtils.closeSession(this.sessionHolder.getSession());
}
}
}
}