Here are the examples of the java api org.hibernate.FlushMode.MANUAL taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.
60 Examples
19
Source : OpenSessionInViewTests.java
with Apache License 2.0
from langtianya
with Apache License 2.0
from langtianya
@Test
public void testOpenSessionInViewInterceptorWithSingleSessionAndJtaTm() throws Exception {
final SessionFactoryImplementor sf = mock(SessionFactoryImplementor.clreplaced);
Session session = mock(Session.clreplaced);
TransactionManager tm = mock(TransactionManager.clreplaced);
given(tm.getTransaction()).willReturn(null);
given(tm.getTransaction()).willReturn(null);
OpenSessionInViewInterceptor interceptor = new OpenSessionInViewInterceptor();
interceptor.setSessionFactory(sf);
given(sf.openSession()).willReturn(session);
given(sf.getTransactionManager()).willReturn(tm);
given(sf.getTransactionManager()).willReturn(tm);
given(session.isOpen()).willReturn(true);
interceptor.preHandle(this.webRequest);
replacedertTrue(TransactionSynchronizationManager.hasResource(sf));
// Check that further invocations simply participate
interceptor.preHandle(this.webRequest);
replacedertEquals(session, SessionFactoryUtils.getSession(sf, false));
interceptor.preHandle(this.webRequest);
interceptor.postHandle(this.webRequest, null);
interceptor.afterCompletion(this.webRequest, null);
interceptor.postHandle(this.webRequest, null);
interceptor.afterCompletion(this.webRequest, null);
interceptor.preHandle(this.webRequest);
interceptor.postHandle(this.webRequest, null);
interceptor.afterCompletion(this.webRequest, null);
interceptor.postHandle(this.webRequest, null);
replacedertTrue(TransactionSynchronizationManager.hasResource(sf));
interceptor.afterCompletion(this.webRequest, null);
replacedertFalse(TransactionSynchronizationManager.hasResource(sf));
verify(session).setFlushMode(FlushMode.MANUAL);
verify(session).close();
}
19
Source : HibernateInterceptorTests.java
with Apache License 2.0
from langtianya
with Apache License 2.0
from langtianya
@Test
public void testInterceptorWithNewSessionAndFlushNever() throws HibernateException {
HibernateInterceptor interceptor = new HibernateInterceptor();
interceptor.setFlushModeName("FLUSH_NEVER");
interceptor.setSessionFactory(sessionFactory);
try {
interceptor.invoke(invocation);
} catch (Throwable t) {
fail("Should not have thrown Throwable: " + t.getMessage());
}
verify(session).setFlushMode(FlushMode.MANUAL);
verify(session, never()).flush();
verify(session).close();
}
19
Source : AbstractPersistentCollection.java
with GNU General Public License v2.0
from lamsfoundation
with GNU General Public License v2.0
from lamsfoundation
private SharedSessionContractImplementor openTemporarySessionForLoading() {
if (sessionFactoryUuid == null) {
throwLazyInitializationException("SessionFactory UUID not known to create temporary Session for loading");
}
final SessionFactoryImplementor sf = (SessionFactoryImplementor) SessionFactoryRegistry.INSTANCE.getSessionFactory(sessionFactoryUuid);
final SharedSessionContractImplementor session = (SharedSessionContractImplementor) sf.openSession();
session.getPersistenceContext().setDefaultReadOnly(true);
session.setFlushMode(FlushMode.MANUAL);
return session;
}
19
Source : StageSessionImpl.java
with GNU Lesser General Public License v2.1
from hibernate
with GNU Lesser General Public License v2.1
from hibernate
@Override
public FlushMode getFlushMode() {
switch(delegate.getHibernateFlushMode()) {
case MANUAL:
return FlushMode.MANUAL;
case COMMIT:
return FlushMode.COMMIT;
case AUTO:
return FlushMode.AUTO;
case ALWAYS:
return FlushMode.ALWAYS;
default:
throw new IllegalStateException("impossible flush mode");
}
}
19
Source : MutinySessionImpl.java
with GNU Lesser General Public License v2.1
from hibernate
with GNU Lesser General Public License v2.1
from hibernate
@Override
public Mutiny.Session setFlushMode(FlushMode flushMode) {
switch(flushMode) {
case COMMIT:
delegate.setHibernateFlushMode(FlushMode.COMMIT);
break;
case AUTO:
delegate.setHibernateFlushMode(FlushMode.AUTO);
break;
case MANUAL:
delegate.setHibernateFlushMode(FlushMode.MANUAL);
break;
case ALWAYS:
delegate.setHibernateFlushMode(FlushMode.ALWAYS);
break;
}
return this;
}
18
Source : HibernateEntityManagerFactoryIntegrationTests.java
with MIT License
from Vip-Augus
with MIT License
from Vip-Augus
// SPR-16956
@Test
public void testReadOnly() {
replacedertSame(FlushMode.AUTO, sharedEnreplacedyManager.unwrap(Session.clreplaced).getHibernateFlushMode());
replacedertFalse(sharedEnreplacedyManager.unwrap(Session.clreplaced).isDefaultReadOnly());
endTransaction();
this.transactionDefinition.setReadOnly(true);
startNewTransaction();
replacedertSame(FlushMode.MANUAL, sharedEnreplacedyManager.unwrap(Session.clreplaced).getHibernateFlushMode());
replacedertTrue(sharedEnreplacedyManager.unwrap(Session.clreplaced).isDefaultReadOnly());
}
18
Source : HibernateTemplateTests.java
with Apache License 2.0
from langtianya
with Apache License 2.0
from langtianya
@Test
public void testSaveOrUpdateWithFlushModeNever() {
TestBean tb = new TestBean();
given(session.getFlushMode()).willReturn(FlushMode.MANUAL);
try {
hibernateTemplate.saveOrUpdate(tb);
fail("Should have thrown InvalidDataAccessApiUsageException");
} catch (InvalidDataAccessApiUsageException ex) {
// expected
}
}
18
Source : OpenSessionInViewTests.java
with Apache License 2.0
from langtianya
with Apache License 2.0
from langtianya
@Test
public void testOpenSessionInViewInterceptorWithSingleSession() throws Exception {
SessionFactory sf = mock(SessionFactory.clreplaced);
Session session = mock(Session.clreplaced);
OpenSessionInViewInterceptor interceptor = new OpenSessionInViewInterceptor();
interceptor.setSessionFactory(sf);
given(sf.openSession()).willReturn(session);
given(session.getSessionFactory()).willReturn(sf);
given(session.getSessionFactory()).willReturn(sf);
given(session.isOpen()).willReturn(true);
interceptor.preHandle(this.webRequest);
replacedertTrue(TransactionSynchronizationManager.hasResource(sf));
// check that further invocations simply participate
interceptor.preHandle(this.webRequest);
replacedertEquals(session, SessionFactoryUtils.getSession(sf, false));
interceptor.preHandle(this.webRequest);
interceptor.postHandle(this.webRequest, null);
interceptor.afterCompletion(this.webRequest, null);
interceptor.postHandle(this.webRequest, null);
interceptor.afterCompletion(this.webRequest, null);
interceptor.preHandle(this.webRequest);
interceptor.postHandle(this.webRequest, null);
interceptor.afterCompletion(this.webRequest, null);
interceptor.postHandle(this.webRequest, null);
replacedertTrue(TransactionSynchronizationManager.hasResource(sf));
interceptor.afterCompletion(this.webRequest, null);
replacedertFalse(TransactionSynchronizationManager.hasResource(sf));
verify(session).setFlushMode(FlushMode.MANUAL);
verify(session).close();
}
18
Source : OpenSessionInViewTests.java
with Apache License 2.0
from langtianya
with Apache License 2.0
from langtianya
@Test
public void testOpenSessionInterceptor() throws Exception {
final SessionFactory sf = mock(SessionFactory.clreplaced);
final Session session = mock(Session.clreplaced);
OpenSessionInterceptor interceptor = new OpenSessionInterceptor();
interceptor.setSessionFactory(sf);
Runnable tb = new Runnable() {
@Override
public void run() {
replacedertTrue(TransactionSynchronizationManager.hasResource(sf));
replacedertEquals(session, SessionFactoryUtils.getSession(sf, false));
}
};
ProxyFactory pf = new ProxyFactory(tb);
pf.addAdvice(interceptor);
Runnable tbProxy = (Runnable) pf.getProxy();
given(sf.openSession()).willReturn(session);
given(session.isOpen()).willReturn(true);
tbProxy.run();
verify(session).setFlushMode(FlushMode.MANUAL);
verify(session).close();
}
18
Source : HibernateContextDAO.java
with Apache License 2.0
from isstac
with Apache License 2.0
from isstac
/**
* @see org.openmrs.api.db.ContextDAO#getUserByUuid(java.lang.String)
*/
@Override
@Transactional(readOnly = true)
public User getUserByUuid(String uuid) {
// don't flush here in case we're in the AuditableInterceptor. Will cause a StackOverflowEx otherwise
FlushMode flushMode = sessionFactory.getCurrentSession().getFlushMode();
sessionFactory.getCurrentSession().setFlushMode(FlushMode.MANUAL);
User u = (User) sessionFactory.getCurrentSession().createQuery("from User u where u.uuid = :uuid").setString("uuid", uuid).uniqueResult();
// reset the flush mode to whatever it was before
sessionFactory.getCurrentSession().setFlushMode(flushMode);
return u;
}
17
Source : HibernateNativeEntityManagerFactoryIntegrationTests.java
with MIT License
from Vip-Augus
with MIT License
from Vip-Augus
// SPR-16956
@Test
public void testReadOnly() {
replacedertSame(FlushMode.AUTO, sessionFactory.getCurrentSession().getHibernateFlushMode());
replacedertFalse(sessionFactory.getCurrentSession().isDefaultReadOnly());
endTransaction();
this.transactionDefinition.setReadOnly(true);
startNewTransaction();
replacedertSame(FlushMode.MANUAL, sessionFactory.getCurrentSession().getHibernateFlushMode());
replacedertTrue(sessionFactory.getCurrentSession().isDefaultReadOnly());
}
17
Source : OpenSessionInViewInterceptor.java
with MIT License
from Vip-Augus
with MIT License
from Vip-Augus
/**
* Open a Session for the SessionFactory that this interceptor uses.
* <p>The default implementation delegates to the {@link SessionFactory#openSession}
* method and sets the {@link Session}'s flush mode to "MANUAL".
* @return the Session to use
* @throws DataAccessResourceFailureException if the Session could not be created
* @see FlushMode#MANUAL
*/
@SuppressWarnings("deprecation")
protected Session openSession() throws DataAccessResourceFailureException {
try {
Session session = obtainSessionFactory().openSession();
session.setFlushMode(FlushMode.MANUAL);
return session;
} catch (HibernateException ex) {
throw new DataAccessResourceFailureException("Could not open Hibernate Session", ex);
}
}
17
Source : HibernateEntityManagerFactoryIntegrationTests.java
with Apache License 2.0
from SourceHot
with Apache License 2.0
from SourceHot
// SPR-16956
@Test
public void testReadOnly() {
replacedertThat(sharedEnreplacedyManager.unwrap(Session.clreplaced).getHibernateFlushMode()).isSameAs(FlushMode.AUTO);
replacedertThat(sharedEnreplacedyManager.unwrap(Session.clreplaced).isDefaultReadOnly()).isFalse();
endTransaction();
this.transactionDefinition.setReadOnly(true);
startNewTransaction();
replacedertThat(sharedEnreplacedyManager.unwrap(Session.clreplaced).getHibernateFlushMode()).isSameAs(FlushMode.MANUAL);
replacedertThat(sharedEnreplacedyManager.unwrap(Session.clreplaced).isDefaultReadOnly()).isTrue();
}
17
Source : OpenSessionInViewInterceptor.java
with Apache License 2.0
from langtianya
with Apache License 2.0
from langtianya
/**
* Open a Session for the SessionFactory that this interceptor uses.
* <p>The default implementation delegates to the {@link SessionFactory#openSession}
* method and sets the {@link Session}'s flush mode to "MANUAL".
* @return the Session to use
* @throws DataAccessResourceFailureException if the Session could not be created
* @see FlushMode#MANUAL
*/
protected Session openSession() throws DataAccessResourceFailureException {
try {
Session session = getSessionFactory().openSession();
session.setFlushMode(FlushMode.MANUAL);
return session;
} catch (HibernateException ex) {
throw new DataAccessResourceFailureException("Could not open Hibernate Session", ex);
}
}
17
Source : OpenSessionInViewInterceptor.java
with Apache License 2.0
from langtianya
with Apache License 2.0
from langtianya
/**
* Open a Session for the SessionFactory that this interceptor uses.
* <p>The default implementation delegates to the {@link SessionFactory#openSession}
* method and sets the {@link Session}'s flush mode to "MANUAL".
* @return the Session to use
* @throws DataAccessResourceFailureException if the Session could not be created
* @see org.hibernate.FlushMode#MANUAL
*/
protected Session openSession() throws DataAccessResourceFailureException {
try {
Session session = getSessionFactory().openSession();
session.setFlushMode(FlushMode.MANUAL);
return session;
} catch (HibernateException ex) {
throw new DataAccessResourceFailureException("Could not open Hibernate Session", ex);
}
}
17
Source : OpenSessionInViewTests.java
with Apache License 2.0
from langtianya
with Apache License 2.0
from langtianya
@Test
public void testOpenSessionInViewInterceptorAndDeferredClose() throws Exception {
SessionFactory sf = mock(SessionFactory.clreplaced);
Session session = mock(Session.clreplaced);
OpenSessionInViewInterceptor interceptor = new OpenSessionInViewInterceptor();
interceptor.setSessionFactory(sf);
interceptor.setSingleSession(false);
given(sf.openSession()).willReturn(session);
given(session.getSessionFactory()).willReturn(sf);
interceptor.preHandle(this.webRequest);
org.hibernate.Session sess = SessionFactoryUtils.getSession(sf, true);
SessionFactoryUtils.releaseSession(sess, sf);
// check that further invocations simply participate
interceptor.preHandle(this.webRequest);
interceptor.preHandle(this.webRequest);
interceptor.postHandle(this.webRequest, null);
interceptor.afterCompletion(this.webRequest, null);
interceptor.postHandle(this.webRequest, null);
interceptor.afterCompletion(this.webRequest, null);
interceptor.preHandle(this.webRequest);
interceptor.postHandle(this.webRequest, null);
interceptor.afterCompletion(this.webRequest, null);
interceptor.postHandle(this.webRequest, null);
interceptor.afterCompletion(this.webRequest, null);
verify(session).setFlushMode(FlushMode.MANUAL);
verify(session).close();
}
17
Source : FlushModeConverter.java
with GNU General Public License v2.0
from lamsfoundation
with GNU General Public License v2.0
from lamsfoundation
public static FlushMode fromXml(String name) {
// valid values are a subset of all FlushMode possibilities, so we will
// handle the conversion here directly.
// Also, we want to map "never"->MANUAL (rather than NEVER)
if (name == null) {
return null;
}
if ("never".equalsIgnoreCase(name)) {
return FlushMode.MANUAL;
} else if ("auto".equalsIgnoreCase(name)) {
return FlushMode.AUTO;
} else if ("always".equalsIgnoreCase(name)) {
return FlushMode.ALWAYS;
}
// if the incoming value was not null *and* was not one of the pre-defined
// values, we need to throw an exception. This *should never happen if the
// doreplacedent we are processing conforms to the schema...
throw new HibernateException("Unrecognized flush mode : " + name);
}
17
Source : HibernateOrderDAO.java
with Apache License 2.0
from isstac
with Apache License 2.0
from isstac
@Override
public List<Object[]> getOrderFromDatabase(Order order, boolean isOrderADrugOrder) throws APIException {
String sql = "SELECT patient_id, care_setting, concept_id FROM orders WHERE order_id = :orderId";
if (isOrderADrugOrder) {
sql = " SELECT o.patient_id, o.care_setting, o.concept_id, d.drug_inventory_id " + " FROM orders o, drug_order d WHERE o.order_id = d.order_id AND o.order_id = :orderId";
}
Query query = sessionFactory.getCurrentSession().createSQLQuery(sql);
query.setParameter("orderId", order.getOrderId());
// prevent hibernate from flushing before fetching the list
query.setFlushMode(FlushMode.MANUAL);
return query.list();
}
17
Source : HibernateContextDAO.java
with Apache License 2.0
from isstac
with Apache License 2.0
from isstac
@Override
public void openSession() {
log.debug("HibernateContext: Opening Hibernate Session");
if (TransactionSynchronizationManager.hasResource(sessionFactory)) {
if (log.isDebugEnabled()) {
log.debug("Participating in existing session (" + sessionFactory.hashCode() + ")");
}
participate = true;
} else {
if (log.isDebugEnabled()) {
log.debug("Registering session with synchronization manager (" + sessionFactory.hashCode() + ")");
}
Session session = sessionFactory.openSession();
session.setFlushMode(FlushMode.MANUAL);
TransactionSynchronizationManager.bindResource(sessionFactory, new SessionHolder(session));
}
}
17
Source : HibernateUtilsTest.java
with Apache License 2.0
from IBM
with Apache License 2.0
from IBM
private static Stream<Arguments> flushModeArguments() {
return Stream.of(Arguments.of(FlushMode.MANUAL, TransactionDefinition.builder().isReadonly(true).build(), null, FlushMode.MANUAL), Arguments.of(FlushMode.AUTO, TransactionDefinition.builder().isReadonly(true).build(), FlushMode.AUTO, FlushMode.MANUAL), Arguments.of(FlushMode.MANUAL, TransactionDefinition.builder().build(), FlushMode.MANUAL, FlushMode.AUTO));
}
16
Source : HibernateJpaDialect.java
with MIT License
from Vip-Augus
with MIT License
from Vip-Augus
@SuppressWarnings("deprecation")
@Nullable
protected FlushMode prepareFlushMode(Session session, boolean readOnly) throws PersistenceException {
FlushMode flushMode = (FlushMode) ReflectionUtils.invokeMethod(getFlushMode, session);
replacedert.state(flushMode != null, "No FlushMode from Session");
if (readOnly) {
// We should suppress flushing for a read-only transaction.
if (!flushMode.equals(FlushMode.MANUAL)) {
session.setFlushMode(FlushMode.MANUAL);
return flushMode;
}
} else {
// We need AUTO or COMMIT for a non-read-only transaction.
if (flushMode.lessThan(FlushMode.COMMIT)) {
session.setFlushMode(FlushMode.AUTO);
return flushMode;
}
}
// No FlushMode change needed...
return null;
}
16
Source : OpenSessionInViewFilter.java
with MIT License
from Vip-Augus
with MIT License
from Vip-Augus
/**
* Open a Session for the SessionFactory that this filter uses.
* <p>The default implementation delegates to the {@link SessionFactory#openSession}
* method and sets the {@link Session}'s flush mode to "MANUAL".
* @param sessionFactory the SessionFactory that this filter uses
* @return the Session to use
* @throws DataAccessResourceFailureException if the Session could not be created
* @see FlushMode#MANUAL
*/
@SuppressWarnings("deprecation")
protected Session openSession(SessionFactory sessionFactory) throws DataAccessResourceFailureException {
try {
Session session = sessionFactory.openSession();
session.setFlushMode(FlushMode.MANUAL);
return session;
} catch (HibernateException ex) {
throw new DataAccessResourceFailureException("Could not open Hibernate Session", ex);
}
}
16
Source : SpringJtaSessionContext.java
with MIT License
from Vip-Augus
with MIT License
from Vip-Augus
@Override
@SuppressWarnings("deprecation")
protected Session buildOrObtainSession() {
Session session = super.buildOrObtainSession();
if (TransactionSynchronizationManager.isCurrentTransactionReadOnly()) {
session.setFlushMode(FlushMode.MANUAL);
}
return session;
}
16
Source : HibernateTemplate.java
with MIT License
from Vip-Augus
with MIT License
from Vip-Augus
/**
* Execute the action specified by the given action object within a Session.
* @param action callback object that specifies the Hibernate action
* @param enforceNativeSession whether to enforce exposure of the native
* Hibernate Session to callback code
* @return a result object returned by the action, or {@code null}
* @throws DataAccessException in case of Hibernate errors
*/
@SuppressWarnings("deprecation")
@Nullable
protected <T> T doExecute(HibernateCallback<T> action, boolean enforceNativeSession) throws DataAccessException {
replacedert.notNull(action, "Callback object must not be null");
Session session = null;
boolean isNew = false;
try {
session = obtainSessionFactory().getCurrentSession();
} catch (HibernateException ex) {
logger.debug("Could not retrieve pre-bound Hibernate session", ex);
}
if (session == null) {
session = obtainSessionFactory().openSession();
session.setFlushMode(FlushMode.MANUAL);
isNew = true;
}
try {
enableFilters(session);
Session sessionToExpose = (enforceNativeSession || isExposeNativeSession() ? session : createSessionProxy(session));
return action.doInHibernate(sessionToExpose);
} catch (HibernateException ex) {
throw SessionFactoryUtils.convertHibernateAccessException(ex);
} catch (PersistenceException ex) {
if (ex.getCause() instanceof HibernateException) {
throw SessionFactoryUtils.convertHibernateAccessException((HibernateException) ex.getCause());
}
throw ex;
} catch (RuntimeException ex) {
// Callback code threw application exception...
throw ex;
} finally {
if (isNew) {
SessionFactoryUtils.closeSession(session);
} else {
disableFilters(session);
}
}
}
16
Source : HibernateNativeEntityManagerFactoryIntegrationTests.java
with Apache License 2.0
from SourceHot
with Apache License 2.0
from SourceHot
// SPR-16956
@Test
public void testReadOnly() {
replacedertThat(sessionFactory.getCurrentSession().getHibernateFlushMode()).isSameAs(FlushMode.AUTO);
replacedertThat(sessionFactory.getCurrentSession().isDefaultReadOnly()).isFalse();
endTransaction();
this.transactionDefinition.setReadOnly(true);
startNewTransaction();
replacedertThat(sessionFactory.getCurrentSession().getHibernateFlushMode()).isSameAs(FlushMode.MANUAL);
replacedertThat(sessionFactory.getCurrentSession().isDefaultReadOnly()).isTrue();
}
16
Source : SqlAuditServiceImpl.java
with Apache License 2.0
from Pardus-Engerek
with Apache License 2.0
from Pardus-Engerek
public long countObjects(String query, Map<String, Object> params) {
Session session = null;
long count = 0;
try {
session = baseHelper.beginTransaction();
session.setFlushMode(FlushMode.MANUAL);
if (StringUtils.isBlank(query)) {
query = "select count (*) from RAuditEventRecord as aer where 1 = 1";
}
Query q = session.createQuery(query);
setParametersToQuery(q, params);
Number numberCount = (Number) q.uniqueResult();
count = numberCount != null ? numberCount.intValue() : 0;
} catch (RuntimeException ex) {
baseHelper.handleGeneralRuntimeException(ex, session, null);
} finally {
baseHelper.cleanupSessionAndResult(session, null);
}
return count;
}
16
Source : SpringJtaSessionContext.java
with Apache License 2.0
from langtianya
with Apache License 2.0
from langtianya
@Override
protected Session buildOrObtainSession() {
Session session = super.buildOrObtainSession();
if (TransactionSynchronizationManager.isCurrentTransactionReadOnly()) {
session.setFlushMode(FlushMode.MANUAL);
}
return session;
}
16
Source : HibernateTemplate.java
with Apache License 2.0
from langtianya
with Apache License 2.0
from langtianya
/**
* Execute the action specified by the given action object within a Session.
* @param action callback object that specifies the Hibernate action
* @param enforceNativeSession whether to enforce exposure of the native
* Hibernate Session to callback code
* @return a result object returned by the action, or {@code null}
* @throws DataAccessException in case of Hibernate errors
*/
protected <T> T doExecute(HibernateCallback<T> action, boolean enforceNativeSession) throws DataAccessException {
replacedert.notNull(action, "Callback object must not be null");
Session session = null;
boolean isNew = false;
try {
session = getSessionFactory().getCurrentSession();
} catch (HibernateException ex) {
logger.debug("Could not retrieve pre-bound Hibernate session", ex);
}
if (session == null) {
session = getSessionFactory().openSession();
session.setFlushMode(FlushMode.MANUAL);
isNew = true;
}
try {
enableFilters(session);
Session sessionToExpose = (enforceNativeSession || isExposeNativeSession() ? session : createSessionProxy(session));
return action.doInHibernate(sessionToExpose);
} catch (HibernateException ex) {
throw SessionFactoryUtils.convertHibernateAccessException(ex);
} catch (RuntimeException ex) {
// Callback code threw application exception...
throw ex;
} finally {
if (isNew) {
SessionFactoryUtils.closeSession(session);
} else {
disableFilters(session);
}
}
}
16
Source : HibernateTemplate.java
with Apache License 2.0
from langtianya
with Apache License 2.0
from langtianya
/**
* Execute the action specified by the given action object within a Session.
* @param action callback object that specifies the Hibernate action
* @param enforceNativeSession whether to enforce exposure of the native
* Hibernate Session to callback code
* @return a result object returned by the action, or {@code null}
* @throws org.springframework.dao.DataAccessException in case of Hibernate errors
*/
protected <T> T doExecute(HibernateCallback<T> action, boolean enforceNativeSession) throws DataAccessException {
replacedert.notNull(action, "Callback object must not be null");
Session session = null;
boolean isNew = false;
try {
session = getSessionFactory().getCurrentSession();
} catch (HibernateException ex) {
logger.debug("Could not retrieve pre-bound Hibernate session", ex);
}
if (session == null) {
session = getSessionFactory().openSession();
session.setFlushMode(FlushMode.MANUAL);
isNew = true;
}
try {
enableFilters(session);
Session sessionToExpose = (enforceNativeSession || isExposeNativeSession() ? session : createSessionProxy(session));
return action.doInHibernate(sessionToExpose);
} catch (HibernateException ex) {
throw SessionFactoryUtils.convertHibernateAccessException(ex);
} catch (RuntimeException ex) {
// Callback code threw application exception...
throw ex;
} finally {
if (isNew) {
SessionFactoryUtils.closeSession(session);
} else {
disableFilters(session);
}
}
}
16
Source : OpenSessionInViewTests.java
with Apache License 2.0
from langtianya
with Apache License 2.0
from langtianya
@Test
public void testOpenSessionInViewInterceptorAsyncScenario() throws Exception {
// Initial request thread
final SessionFactory sf = mock(SessionFactory.clreplaced);
Session session = mock(Session.clreplaced);
OpenSessionInViewInterceptor interceptor = new OpenSessionInViewInterceptor();
interceptor.setSessionFactory(sf);
given(sf.openSession()).willReturn(session);
given(session.getSessionFactory()).willReturn(sf);
interceptor.preHandle(this.webRequest);
replacedertTrue(TransactionSynchronizationManager.hasResource(sf));
AsyncWebRequest asyncWebRequest = new StandardServletAsyncWebRequest(this.request, this.response);
WebAsyncManager asyncManager = WebAsyncUtils.getAsyncManager(this.request);
asyncManager.setTaskExecutor(new SyncTaskExecutor());
asyncManager.setAsyncWebRequest(asyncWebRequest);
asyncManager.startCallableProcessing(new Callable<String>() {
@Override
public String call() throws Exception {
return "anything";
}
});
interceptor.afterConcurrentHandlingStarted(this.webRequest);
replacedertFalse(TransactionSynchronizationManager.hasResource(sf));
// Async dispatch thread
interceptor.preHandle(this.webRequest);
replacedertTrue("Session not bound to async thread", TransactionSynchronizationManager.hasResource(sf));
interceptor.postHandle(this.webRequest, null);
replacedertTrue(TransactionSynchronizationManager.hasResource(sf));
verify(session, never()).close();
interceptor.afterCompletion(this.webRequest, null);
replacedertFalse(TransactionSynchronizationManager.hasResource(sf));
verify(session).setFlushMode(FlushMode.MANUAL);
verify(session).close();
}
16
Source : Helper.java
with GNU General Public License v2.0
from lamsfoundation
with GNU General Public License v2.0
from lamsfoundation
private SharedSessionContractImplementor openTemporarySessionForLoading(LazyInitializationWork lazyInitializationWork) {
if (consumer.getSessionFactoryUuid() == null) {
throwLazyInitializationException(Cause.NO_SF_UUID, lazyInitializationWork);
}
final SessionFactoryImplementor sf = (SessionFactoryImplementor) SessionFactoryRegistry.INSTANCE.getSessionFactory(consumer.getSessionFactoryUuid());
final SharedSessionContractImplementor session = (SharedSessionContractImplementor) sf.openSession();
session.getPersistenceContext().setDefaultReadOnly(true);
session.setHibernateFlushMode(FlushMode.MANUAL);
return session;
}
16
Source : HibernateProgramWorkflowDAO.java
with Apache License 2.0
from isstac
with Apache License 2.0
from isstac
@Override
public List<PatientProgram> getPatientProgramByAttributeNameAndValue(String attributeName, String attributeValue) {
FlushMode flushMode = sessionFactory.getCurrentSession().getFlushMode();
sessionFactory.getCurrentSession().setFlushMode(FlushMode.MANUAL);
Query query;
try {
query = sessionFactory.getCurrentSession().createQuery("SELECT pp FROM patient_program pp " + "INNER JOIN pp.attributes attr " + "INNER JOIN attr.attributeType attr_type " + "WHERE attr.valueReference = :attributeValue " + "AND attr_type.name = :attributeName " + "AND pp.voided = 0").setParameter("attributeName", attributeName).setParameter("attributeValue", attributeValue);
return query.list();
} finally {
sessionFactory.getCurrentSession().setFlushMode(flushMode);
}
}
16
Source : HibernateContextDAO.java
with Apache License 2.0
from isstac
with Apache License 2.0
from isstac
@Override
@Transactional
public void updateSearchIndexForType(Clreplaced<?> type) {
// From http://docs.jboss.org/hibernate/search/3.3/reference/en-US/html/manual-index-changes.html#search-batchindex-flushtoindexes
FullTextSession session = Search.getFullTextSession(sessionFactory.getCurrentSession());
session.purgeAll(type);
// Prepare session for batch work
session.flush();
session.clear();
FlushMode flushMode = session.getFlushMode();
CacheMode cacheMode = session.getCacheMode();
try {
session.setFlushMode(FlushMode.MANUAL);
session.setCacheMode(CacheMode.IGNORE);
// Scrollable results will avoid loading too many objects in memory
ScrollableResults results = session.createCriteria(type).setFetchSize(1000).scroll(ScrollMode.FORWARD_ONLY);
int index = 0;
while (results.next()) {
index++;
// index each element
session.index(results.get(0));
if (index % 1000 == 0) {
// apply changes to indexes
session.flushToIndexes();
// free memory since the queue is processed
session.clear();
}
}
session.flushToIndexes();
session.clear();
} finally {
session.setFlushMode(flushMode);
session.setCacheMode(cacheMode);
}
}
15
Source : OpenSessionInterceptor.java
with MIT License
from Vip-Augus
with MIT License
from Vip-Augus
/**
* Open a Session for the given SessionFactory.
* <p>The default implementation delegates to the {@link SessionFactory#openSession}
* method and sets the {@link Session}'s flush mode to "MANUAL".
* @param sessionFactory the SessionFactory to use
* @return the Session to use
* @throws DataAccessResourceFailureException if the Session could not be created
* @since 5.0
* @see FlushMode#MANUAL
*/
@SuppressWarnings("deprecation")
protected Session openSession(SessionFactory sessionFactory) throws DataAccessResourceFailureException {
Session session = openSession();
if (session == null) {
try {
session = sessionFactory.openSession();
session.setFlushMode(FlushMode.MANUAL);
} catch (HibernateException ex) {
throw new DataAccessResourceFailureException("Could not open Hibernate Session", ex);
}
}
return session;
}
15
Source : HibernateFilter.java
with Apache License 2.0
from openequella
with Apache License 2.0
from openequella
/**
* Prior to hibernate 5, oEQ never touched the FlushMode. Due to changes in Spring and Hibernate,
* `openSession` was added and followed the flow of the Spring impl of `openSession`.
*
* <p>FlushMode is set to MANUAL to reduce surprise flushes to the database, and it'll switch to
* AUTO in a non-read-only transaction, and then flip back.
*
* <p>The internal transaction handling logic with respect to flush mode appears to remain
* unchanged
*
* @param sessionFactory
* @return
*/
private Session openSession(SessionFactory sessionFactory) {
Session session = sessionFactory.openSession();
session.setHibernateFlushMode(FlushMode.MANUAL);
return session;
}
15
Source : OpenSessionInViewFilter.java
with Apache License 2.0
from langtianya
with Apache License 2.0
from langtianya
/**
* Open a Session for the SessionFactory that this filter uses.
* <p>The default implementation delegates to the {@link SessionFactory#openSession}
* method and sets the {@link Session}'s flush mode to "MANUAL".
* @param sessionFactory the SessionFactory that this filter uses
* @return the Session to use
* @throws DataAccessResourceFailureException if the Session could not be created
* @see FlushMode#MANUAL
*/
protected Session openSession(SessionFactory sessionFactory) throws DataAccessResourceFailureException {
try {
Session session = sessionFactory.openSession();
session.setFlushMode(FlushMode.MANUAL);
return session;
} catch (HibernateException ex) {
throw new DataAccessResourceFailureException("Could not open Hibernate Session", ex);
}
}
15
Source : OpenSessionInViewFilter.java
with Apache License 2.0
from langtianya
with Apache License 2.0
from langtianya
/**
* Open a Session for the SessionFactory that this filter uses.
* <p>The default implementation delegates to the {@link SessionFactory#openSession}
* method and sets the {@link Session}'s flush mode to "MANUAL".
* @param sessionFactory the SessionFactory that this filter uses
* @return the Session to use
* @throws DataAccessResourceFailureException if the Session could not be created
* @see org.hibernate.FlushMode#MANUAL
*/
protected Session openSession(SessionFactory sessionFactory) throws DataAccessResourceFailureException {
try {
Session session = sessionFactory.openSession();
session.setFlushMode(FlushMode.MANUAL);
return session;
} catch (HibernateException ex) {
throw new DataAccessResourceFailureException("Could not open Hibernate Session", ex);
}
}
15
Source : HibernateJpaDialect.java
with Apache License 2.0
from langtianya
with Apache License 2.0
from langtianya
protected FlushMode prepareFlushMode(Session session, boolean readOnly) throws PersistenceException {
FlushMode flushMode = session.getFlushMode();
if (readOnly) {
// We should suppress flushing for a read-only transaction.
if (!flushMode.equals(FlushMode.MANUAL)) {
session.setFlushMode(FlushMode.MANUAL);
return flushMode;
}
} else {
// We need AUTO or COMMIT for a non-read-only transaction.
if (flushMode.lessThan(FlushMode.COMMIT)) {
session.setFlushMode(FlushMode.AUTO);
return flushMode;
}
}
// No FlushMode change needed...
return null;
}
15
Source : SessionFactoryUtils.java
with Apache License 2.0
from langtianya
with Apache License 2.0
from langtianya
/**
* Close the given Session or register it for deferred close.
* @param session the Hibernate Session to close
* @param sessionFactory Hibernate SessionFactory that the Session was created with
* (may be {@code null})
* @see #initDeferredClose
* @see #processDeferredClose
*/
static void closeSessionOrRegisterDeferredClose(Session session, SessionFactory sessionFactory) {
Map<SessionFactory, Set<Session>> holderMap = deferredCloseHolder.get();
if (holderMap != null && sessionFactory != null && holderMap.containsKey(sessionFactory)) {
logger.debug("Registering Hibernate Session for deferred close");
// Switch Session to FlushMode.MANUAL for remaining lifetime.
session.setFlushMode(FlushMode.MANUAL);
Set<Session> sessions = holderMap.get(sessionFactory);
sessions.add(session);
} else {
closeSession(session);
}
}
15
Source : HibernateTransactionManager.java
with Apache License 2.0
from langtianya
with Apache License 2.0
from langtianya
@Override
protected void prepareForCommit(DefaultTransactionStatus status) {
if (this.earlyFlushBeforeCommit && status.isNewTransaction()) {
HibernateTransactionObject txObject = (HibernateTransactionObject) status.getTransaction();
Session session = txObject.getSessionHolder().getSession();
if (!session.getFlushMode().lessThan(FlushMode.COMMIT)) {
logger.debug("Performing an early flush for Hibernate transaction");
try {
session.flush();
} catch (HibernateException ex) {
throw convertHibernateAccessException(ex);
} finally {
session.setFlushMode(FlushMode.MANUAL);
}
}
}
}
15
Source : NamedQueryCollectionInitializer.java
with GNU General Public License v2.0
from lamsfoundation
with GNU General Public License v2.0
from lamsfoundation
public void initialize(Serializable key, SharedSessionContractImplementor session) throws HibernateException {
LOG.debugf("Initializing collection: %s using named query: %s", persister.getRole(), queryName);
NativeQueryImplementor nativeQuery = session.getNamedNativeQuery(queryName);
if (nativeQuery.getParameterMetadata().hasNamedParameters()) {
nativeQuery.setParameter(nativeQuery.getParameterMetadata().getNamedParameterNames().iterator().next(), key, persister.getKeyType());
} else {
nativeQuery.setParameter(1, key, persister.getKeyType());
}
nativeQuery.setCollectionKey(key).setFlushMode(FlushMode.MANUAL).list();
}
15
Source : HibernateEncounterDAO.java
with Apache License 2.0
from isstac
with Apache License 2.0
from isstac
/**
* @see org.openmrs.api.db.EncounterDAO#getSavedEncounterDatetime(org.openmrs.Encounter)
*/
@Override
public Date getSavedEncounterDatetime(Encounter encounter) {
// Usages of this method currently are internal and don't require a flush
// Otherwise we end up with premature flushes of Immutable types like Obs
// that are replacedociated to the encounter before we void and replace them
Session session = sessionFactory.getCurrentSession();
FlushMode flushMode = session.getFlushMode();
session.setFlushMode(FlushMode.MANUAL);
try {
SQLQuery sql = session.createSQLQuery("select encounter_datetime from encounter where encounter_id = :encounterId");
sql.setInteger("encounterId", encounter.getEncounterId());
return (Date) sql.uniqueResult();
} finally {
session.setFlushMode(flushMode);
}
}
15
Source : HibernateEncounterDAO.java
with Apache License 2.0
from isstac
with Apache License 2.0
from isstac
/**
* @see org.openmrs.api.db.EncounterDAO#getSavedEncounterLocation(org.openmrs.Encounter)
*/
@Override
public Location getSavedEncounterLocation(Encounter encounter) {
Session session = sessionFactory.getCurrentSession();
FlushMode flushMode = session.getFlushMode();
session.setFlushMode(FlushMode.MANUAL);
try {
SQLQuery sql = session.createSQLQuery("select location_id from encounter where encounter_id = :encounterId");
sql.setInteger("encounterId", encounter.getEncounterId());
return Context.getLocationService().getLocation((Integer) sql.uniqueResult());
} finally {
session.setFlushMode(flushMode);
}
}
14
Source : OpenSessionInViewTests.java
with Apache License 2.0
from langtianya
with Apache License 2.0
from langtianya
@Test
public void testOpenSessionInViewFilterWithDeferredCloseAndAlreadyActiveDeferredClose() throws Exception {
final SessionFactory sf = mock(SessionFactory.clreplaced);
final Session session = mock(Session.clreplaced);
given(sf.openSession()).willReturn(session);
given(session.getSessionFactory()).willReturn(sf);
given(session.getFlushMode()).willReturn(FlushMode.MANUAL);
StaticWebApplicationContext wac = new StaticWebApplicationContext();
wac.setServletContext(sc);
wac.getDefaultListableBeanFactory().registerSingleton("sessionFactory", sf);
wac.refresh();
sc.setAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE, wac);
MockFilterConfig filterConfig = new MockFilterConfig(wac.getServletContext(), "filter");
MockFilterConfig filterConfig2 = new MockFilterConfig(wac.getServletContext(), "filter2");
filterConfig.addInitParameter("singleSession", "false");
filterConfig2.addInitParameter("singleSession", "false");
filterConfig2.addInitParameter("sessionFactoryBeanName", "mySessionFactory");
OpenSessionInViewInterceptor interceptor = new OpenSessionInViewInterceptor();
interceptor.setSessionFactory(sf);
interceptor.setSingleSession(false);
interceptor.preHandle(webRequest);
final OpenSessionInViewFilter filter = new OpenSessionInViewFilter();
filter.init(filterConfig);
final OpenSessionInViewFilter filter2 = new OpenSessionInViewFilter();
filter2.init(filterConfig2);
final FilterChain filterChain = new FilterChain() {
@Override
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse) {
HibernateTransactionManager tm = new HibernateTransactionManager(sf);
TransactionStatus ts = tm.getTransaction(new DefaultTransactionDefinition(TransactionDefinition.PROPAGATION_SUPPORTS));
org.hibernate.Session sess = SessionFactoryUtils.getSession(sf, true);
SessionFactoryUtils.releaseSession(sess, sf);
tm.commit(ts);
servletRequest.setAttribute("invoked", Boolean.TRUE);
}
};
FilterChain filterChain2 = new FilterChain() {
@Override
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse) throws IOException, ServletException {
filter.doFilter(servletRequest, servletResponse, filterChain);
}
};
filter.doFilter(this.request, this.response, filterChain2);
replacedertNotNull(this.request.getAttribute("invoked"));
interceptor.postHandle(webRequest, null);
interceptor.afterCompletion(webRequest, null);
verify(session).setFlushMode(FlushMode.MANUAL);
verify(session).close();
wac.close();
}
14
Source : OpenSessionInViewTests.java
with Apache License 2.0
from langtianya
with Apache License 2.0
from langtianya
@Test
public void testOpenSessionInViewFilterWithSingleSessionAndPreBoundSession() throws Exception {
final SessionFactory sf = mock(SessionFactory.clreplaced);
Session session = mock(Session.clreplaced);
given(sf.openSession()).willReturn(session);
given(session.getSessionFactory()).willReturn(sf);
StaticWebApplicationContext wac = new StaticWebApplicationContext();
wac.setServletContext(sc);
wac.getDefaultListableBeanFactory().registerSingleton("sessionFactory", sf);
wac.refresh();
sc.setAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE, wac);
MockFilterConfig filterConfig = new MockFilterConfig(wac.getServletContext(), "filter");
MockFilterConfig filterConfig2 = new MockFilterConfig(wac.getServletContext(), "filter2");
filterConfig2.addInitParameter("sessionFactoryBeanName", "mySessionFactory");
OpenSessionInViewInterceptor interceptor = new OpenSessionInViewInterceptor();
interceptor.setSessionFactory(sf);
interceptor.preHandle(this.webRequest);
final OpenSessionInViewFilter filter = new OpenSessionInViewFilter();
filter.init(filterConfig);
final FilterChain filterChain = new FilterChain() {
@Override
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse) {
replacedertTrue(TransactionSynchronizationManager.hasResource(sf));
servletRequest.setAttribute("invoked", Boolean.TRUE);
}
};
replacedertTrue(TransactionSynchronizationManager.hasResource(sf));
filter.doFilter(this.request, this.response, filterChain);
replacedertTrue(TransactionSynchronizationManager.hasResource(sf));
replacedertNotNull(this.request.getAttribute("invoked"));
interceptor.postHandle(this.webRequest, null);
interceptor.afterCompletion(this.webRequest, null);
verify(session).setFlushMode(FlushMode.MANUAL);
verify(session).close();
wac.close();
}
14
Source : AbstractLazyInitializer.java
with GNU General Public License v2.0
from lamsfoundation
with GNU General Public License v2.0
from lamsfoundation
protected void permissiveInitialization() {
if (session == null) {
// we have a detached collection thats set to null, reattach
if (sessionFactoryUuid == null) {
throw new LazyInitializationException("could not initialize proxy [" + enreplacedyName + "#" + id + "] - no Session");
}
try {
SessionFactoryImplementor sf = (SessionFactoryImplementor) SessionFactoryRegistry.INSTANCE.getSessionFactory(sessionFactoryUuid);
SharedSessionContractImplementor session = (SharedSessionContractImplementor) sf.openSession();
session.getPersistenceContext().setDefaultReadOnly(true);
session.setFlushMode(FlushMode.MANUAL);
boolean isJTA = session.getTransactionCoordinator().getTransactionCoordinatorBuilder().isJta();
if (!isJTA) {
// Explicitly handle the transactions only if we're not in
// a JTA environment. A lazy loading temporary session can
// be created even if a current session and transaction are
// open (ex: session.clear() was used). We must prevent
// multiple transactions.
session.beginTransaction();
}
try {
target = session.immediateLoad(enreplacedyName, id);
initialized = true;
checkTargetState(session);
} finally {
// make sure the just opened temp session gets closed!
try {
if (!isJTA) {
session.getTransaction().commit();
}
session.close();
} catch (Exception e) {
LOG.warn("Unable to close temporary session used to load lazy proxy replacedociated to no session");
}
}
} catch (Exception e) {
LOG.error("Initialization failure [" + enreplacedyName + "#" + id + "]", e);
throw new LazyInitializationException(e.getMessage());
}
} else if (session.isOpen() && session.isConnected()) {
target = session.immediateLoad(enreplacedyName, id);
initialized = true;
checkTargetState(session);
} else {
throw new LazyInitializationException("could not initialize proxy [" + enreplacedyName + "#" + id + "] - Session was closed or disced");
}
}
13
Source : SpringSessionContext.java
with MIT License
from Vip-Augus
with MIT License
from Vip-Augus
/**
* Retrieve the Spring-managed Session for the current thread, if any.
*/
@Override
@SuppressWarnings("deprecation")
public Session currentSession() throws HibernateException {
Object value = TransactionSynchronizationManager.getResource(this.sessionFactory);
if (value instanceof Session) {
return (Session) value;
} else if (value instanceof SessionHolder) {
// HibernateTransactionManager
SessionHolder sessionHolder = (SessionHolder) value;
Session session = sessionHolder.getSession();
if (!sessionHolder.isSynchronizedWithTransaction() && TransactionSynchronizationManager.isSynchronizationActive()) {
TransactionSynchronizationManager.registerSynchronization(new SpringSessionSynchronization(sessionHolder, this.sessionFactory, false));
sessionHolder.setSynchronizedWithTransaction(true);
// Switch to FlushMode.AUTO, as we have to replacedume a thread-bound Session
// with FlushMode.MANUAL, which needs to allow flushing within the transaction.
FlushMode flushMode = SessionFactoryUtils.getFlushMode(session);
if (flushMode.equals(FlushMode.MANUAL) && !TransactionSynchronizationManager.isCurrentTransactionReadOnly()) {
session.setFlushMode(FlushMode.AUTO);
sessionHolder.setPreviousFlushMode(flushMode);
}
}
return session;
} else if (value instanceof EnreplacedyManagerHolder) {
// JpaTransactionManager
return ((EnreplacedyManagerHolder) value).getEnreplacedyManager().unwrap(Session.clreplaced);
}
if (this.transactionManager != null && this.jtaSessionContext != null) {
try {
if (this.transactionManager.getStatus() == Status.STATUS_ACTIVE) {
Session session = this.jtaSessionContext.currentSession();
if (TransactionSynchronizationManager.isSynchronizationActive()) {
TransactionSynchronizationManager.registerSynchronization(new SpringFlushSynchronization(session));
}
return session;
}
} catch (SystemException ex) {
throw new HibernateException("JTA TransactionManager found but status check failed", ex);
}
}
if (TransactionSynchronizationManager.isSynchronizationActive()) {
Session session = this.sessionFactory.openSession();
if (TransactionSynchronizationManager.isCurrentTransactionReadOnly()) {
session.setFlushMode(FlushMode.MANUAL);
}
SessionHolder sessionHolder = new SessionHolder(session);
TransactionSynchronizationManager.registerSynchronization(new SpringSessionSynchronization(sessionHolder, this.sessionFactory, true));
TransactionSynchronizationManager.bindResource(this.sessionFactory, sessionHolder);
sessionHolder.setSynchronizedWithTransaction(true);
return session;
} else {
throw new HibernateException("Could not obtain transaction-synchronized Session for current thread");
}
}
13
Source : SpringSessionContext.java
with Apache License 2.0
from langtianya
with Apache License 2.0
from langtianya
/**
* Retrieve the Spring-managed Session for the current thread, if any.
*/
@Override
public Session currentSession() throws HibernateException {
Object value = TransactionSynchronizationManager.getResource(this.sessionFactory);
if (value instanceof Session) {
return (Session) value;
} else if (value instanceof SessionHolder) {
SessionHolder sessionHolder = (SessionHolder) value;
Session session = sessionHolder.getSession();
if (!sessionHolder.isSynchronizedWithTransaction() && TransactionSynchronizationManager.isSynchronizationActive()) {
TransactionSynchronizationManager.registerSynchronization(new SpringSessionSynchronization(sessionHolder, this.sessionFactory, false));
sessionHolder.setSynchronizedWithTransaction(true);
// Switch to FlushMode.AUTO, as we have to replacedume a thread-bound Session
// with FlushMode.MANUAL, which needs to allow flushing within the transaction.
FlushMode flushMode = session.getFlushMode();
if (flushMode.equals(FlushMode.MANUAL) && !TransactionSynchronizationManager.isCurrentTransactionReadOnly()) {
session.setFlushMode(FlushMode.AUTO);
sessionHolder.setPreviousFlushMode(flushMode);
}
}
return session;
}
if (this.transactionManager != null) {
try {
if (this.transactionManager.getStatus() == Status.STATUS_ACTIVE) {
Session session = this.jtaSessionContext.currentSession();
if (TransactionSynchronizationManager.isSynchronizationActive()) {
TransactionSynchronizationManager.registerSynchronization(new SpringFlushSynchronization(session));
}
return session;
}
} catch (SystemException ex) {
throw new HibernateException("JTA TransactionManager found but status check failed", ex);
}
}
if (TransactionSynchronizationManager.isSynchronizationActive()) {
Session session = this.sessionFactory.openSession();
if (TransactionSynchronizationManager.isCurrentTransactionReadOnly()) {
session.setFlushMode(FlushMode.MANUAL);
}
SessionHolder sessionHolder = new SessionHolder(session);
TransactionSynchronizationManager.registerSynchronization(new SpringSessionSynchronization(sessionHolder, this.sessionFactory, true));
TransactionSynchronizationManager.bindResource(this.sessionFactory, sessionHolder);
sessionHolder.setSynchronizedWithTransaction(true);
return session;
} else {
throw new HibernateException("Could not obtain transaction-synchronized Session for current thread");
}
}
13
Source : OpenSessionInViewTests.java
with Apache License 2.0
from langtianya
with Apache License 2.0
from langtianya
@Test
public void testOpenSessionInViewFilterWithSingleSession() throws Exception {
final SessionFactory sf = mock(SessionFactory.clreplaced);
Session session = mock(Session.clreplaced);
given(sf.openSession()).willReturn(session);
given(session.getSessionFactory()).willReturn(sf);
given(session.close()).willReturn(null);
final SessionFactory sf2 = mock(SessionFactory.clreplaced);
Session session2 = mock(Session.clreplaced);
given(sf2.openSession()).willReturn(session2);
given(session2.getSessionFactory()).willReturn(sf2);
given(session2.close()).willReturn(null);
StaticWebApplicationContext wac = new StaticWebApplicationContext();
wac.setServletContext(sc);
wac.getDefaultListableBeanFactory().registerSingleton("sessionFactory", sf);
wac.getDefaultListableBeanFactory().registerSingleton("mySessionFactory", sf2);
wac.refresh();
sc.setAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE, wac);
MockFilterConfig filterConfig = new MockFilterConfig(wac.getServletContext(), "filter");
MockFilterConfig filterConfig2 = new MockFilterConfig(wac.getServletContext(), "filter2");
filterConfig2.addInitParameter("sessionFactoryBeanName", "mySessionFactory");
filterConfig2.addInitParameter("flushMode", "AUTO");
final OpenSessionInViewFilter filter = new OpenSessionInViewFilter();
filter.init(filterConfig);
final OpenSessionInViewFilter filter2 = new OpenSessionInViewFilter();
filter2.init(filterConfig2);
final FilterChain filterChain = new FilterChain() {
@Override
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse) {
replacedertTrue(TransactionSynchronizationManager.hasResource(sf));
servletRequest.setAttribute("invoked", Boolean.TRUE);
}
};
final FilterChain filterChain2 = new FilterChain() {
@Override
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse) throws IOException, ServletException {
replacedertTrue(TransactionSynchronizationManager.hasResource(sf2));
filter.doFilter(servletRequest, servletResponse, filterChain);
}
};
FilterChain filterChain3 = new PreplacedThroughFilterChain(filter2, filterChain2);
replacedertFalse(TransactionSynchronizationManager.hasResource(sf));
replacedertFalse(TransactionSynchronizationManager.hasResource(sf2));
filter2.doFilter(this.request, this.response, filterChain3);
replacedertFalse(TransactionSynchronizationManager.hasResource(sf));
replacedertFalse(TransactionSynchronizationManager.hasResource(sf2));
replacedertNotNull(this.request.getAttribute("invoked"));
verify(session).setFlushMode(FlushMode.MANUAL);
verify(session2).setFlushMode(FlushMode.AUTO);
wac.close();
}
13
Source : HibernateAccessor.java
with Apache License 2.0
from langtianya
with Apache License 2.0
from langtianya
/**
* Apply the flush mode that's been specified for this accessor
* to the given Session.
* @param session the current Hibernate Session
* @param existingTransaction if executing within an existing transaction
* @return the previous flush mode to restore after the operation,
* or {@code null} if none
* @see #setFlushMode
* @see org.hibernate.Session#setFlushMode
*/
protected FlushMode applyFlushMode(Session session, boolean existingTransaction) {
if (getFlushMode() == FLUSH_NEVER) {
if (existingTransaction) {
FlushMode previousFlushMode = session.getFlushMode();
if (!previousFlushMode.lessThan(FlushMode.COMMIT)) {
session.setFlushMode(FlushMode.MANUAL);
return previousFlushMode;
}
} else {
session.setFlushMode(FlushMode.MANUAL);
}
} else if (getFlushMode() == FLUSH_EAGER) {
if (existingTransaction) {
FlushMode previousFlushMode = session.getFlushMode();
if (!previousFlushMode.equals(FlushMode.AUTO)) {
session.setFlushMode(FlushMode.AUTO);
return previousFlushMode;
}
} else {
// rely on default FlushMode.AUTO
}
} else if (getFlushMode() == FLUSH_COMMIT) {
if (existingTransaction) {
FlushMode previousFlushMode = session.getFlushMode();
if (previousFlushMode.equals(FlushMode.AUTO) || previousFlushMode.equals(FlushMode.ALWAYS)) {
session.setFlushMode(FlushMode.COMMIT);
return previousFlushMode;
}
} else {
session.setFlushMode(FlushMode.COMMIT);
}
} else if (getFlushMode() == FLUSH_ALWAYS) {
if (existingTransaction) {
FlushMode previousFlushMode = session.getFlushMode();
if (!previousFlushMode.equals(FlushMode.ALWAYS)) {
session.setFlushMode(FlushMode.ALWAYS);
return previousFlushMode;
}
} else {
session.setFlushMode(FlushMode.ALWAYS);
}
}
return null;
}
See More Examples