Java Code Examples for org.springframework.transaction.support.TransactionTemplate#setReadOnly()

The following examples show how to use org.springframework.transaction.support.TransactionTemplate#setReadOnly() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: DataSourceTransactionManagerTests.java    From spring-analysis-note with MIT License 5 votes vote down vote up
@Test
public void testTransactionWithIsolationAndReadOnly() throws Exception {
	given(con.getTransactionIsolation()).willReturn(Connection.TRANSACTION_READ_COMMITTED);
	given(con.getAutoCommit()).willReturn(true);

	TransactionTemplate tt = new TransactionTemplate(tm);
	tt.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRES_NEW);
	tt.setIsolationLevel(TransactionDefinition.ISOLATION_SERIALIZABLE);
	tt.setReadOnly(true);
	assertTrue("Hasn't thread connection", !TransactionSynchronizationManager.hasResource(ds));
	tt.execute(new TransactionCallbackWithoutResult() {
		@Override
		protected void doInTransactionWithoutResult(TransactionStatus status) {
			assertTrue(TransactionSynchronizationManager.isCurrentTransactionReadOnly());
			assertTrue(TransactionSynchronizationManager.isActualTransactionActive());
			// something transactional
		}
	});

	assertTrue("Hasn't thread connection", !TransactionSynchronizationManager.hasResource(ds));
	InOrder ordered = inOrder(con);
	ordered.verify(con).setTransactionIsolation(Connection.TRANSACTION_SERIALIZABLE);
	ordered.verify(con).setAutoCommit(false);
	ordered.verify(con).commit();
	ordered.verify(con).setAutoCommit(true);
	ordered.verify(con).setTransactionIsolation(Connection.TRANSACTION_READ_COMMITTED);
	verify(con).close();
}
 
Example 2
Source File: DataSourceTransactionManagerTests.java    From spring-analysis-note with MIT License 5 votes vote down vote up
@Test
public void testTransactionWithEnforceReadOnly() throws Exception {
	tm.setEnforceReadOnly(true);

	given(con.getAutoCommit()).willReturn(true);
	Statement stmt = mock(Statement.class);
	given(con.createStatement()).willReturn(stmt);

	TransactionTemplate tt = new TransactionTemplate(tm);
	tt.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRES_NEW);
	tt.setReadOnly(true);
	assertTrue("Hasn't thread connection", !TransactionSynchronizationManager.hasResource(ds));
	tt.execute(new TransactionCallbackWithoutResult() {
		@Override
		protected void doInTransactionWithoutResult(TransactionStatus status) {
			assertTrue(TransactionSynchronizationManager.isCurrentTransactionReadOnly());
			assertTrue(TransactionSynchronizationManager.isActualTransactionActive());
			// something transactional
		}
	});

	assertTrue("Hasn't thread connection", !TransactionSynchronizationManager.hasResource(ds));
	InOrder ordered = inOrder(con, stmt);
	ordered.verify(con).setAutoCommit(false);
	ordered.verify(stmt).executeUpdate("SET TRANSACTION READ ONLY");
	ordered.verify(stmt).close();
	ordered.verify(con).commit();
	ordered.verify(con).setAutoCommit(true);
	ordered.verify(con).close();
}
 
Example 3
Source File: DataSourceTransactionManagerTests.java    From java-technology-stack with MIT License 5 votes vote down vote up
@Test
public void testTransactionWithIsolationAndReadOnly() throws Exception {
	given(con.getTransactionIsolation()).willReturn(Connection.TRANSACTION_READ_COMMITTED);
	given(con.getAutoCommit()).willReturn(true);

	TransactionTemplate tt = new TransactionTemplate(tm);
	tt.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRES_NEW);
	tt.setIsolationLevel(TransactionDefinition.ISOLATION_SERIALIZABLE);
	tt.setReadOnly(true);
	assertTrue("Hasn't thread connection", !TransactionSynchronizationManager.hasResource(ds));
	tt.execute(new TransactionCallbackWithoutResult() {
		@Override
		protected void doInTransactionWithoutResult(TransactionStatus status) {
			assertTrue(TransactionSynchronizationManager.isCurrentTransactionReadOnly());
			assertTrue(TransactionSynchronizationManager.isActualTransactionActive());
			// something transactional
		}
	});

	assertTrue("Hasn't thread connection", !TransactionSynchronizationManager.hasResource(ds));
	InOrder ordered = inOrder(con);
	ordered.verify(con).setTransactionIsolation(Connection.TRANSACTION_SERIALIZABLE);
	ordered.verify(con).setAutoCommit(false);
	ordered.verify(con).commit();
	ordered.verify(con).setAutoCommit(true);
	ordered.verify(con).setTransactionIsolation(Connection.TRANSACTION_READ_COMMITTED);
	verify(con).close();
}
 
Example 4
Source File: DataSourceTransactionManagerTests.java    From java-technology-stack with MIT License 5 votes vote down vote up
@Test
public void testTransactionWithEnforceReadOnly() throws Exception {
	tm.setEnforceReadOnly(true);

	given(con.getAutoCommit()).willReturn(true);
	Statement stmt = mock(Statement.class);
	given(con.createStatement()).willReturn(stmt);

	TransactionTemplate tt = new TransactionTemplate(tm);
	tt.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRES_NEW);
	tt.setReadOnly(true);
	assertTrue("Hasn't thread connection", !TransactionSynchronizationManager.hasResource(ds));
	tt.execute(new TransactionCallbackWithoutResult() {
		@Override
		protected void doInTransactionWithoutResult(TransactionStatus status) {
			assertTrue(TransactionSynchronizationManager.isCurrentTransactionReadOnly());
			assertTrue(TransactionSynchronizationManager.isActualTransactionActive());
			// something transactional
		}
	});

	assertTrue("Hasn't thread connection", !TransactionSynchronizationManager.hasResource(ds));
	InOrder ordered = inOrder(con, stmt);
	ordered.verify(con).setAutoCommit(false);
	ordered.verify(stmt).executeUpdate("SET TRANSACTION READ ONLY");
	ordered.verify(stmt).close();
	ordered.verify(con).commit();
	ordered.verify(con).setAutoCommit(true);
	ordered.verify(con).close();
}
 
Example 5
Source File: DataSourceTransactionManagerTests.java    From spring4-understanding with Apache License 2.0 5 votes vote down vote up
@Test
public void testTransactionWithIsolationAndReadOnly() throws Exception {
	given(con.getTransactionIsolation()).willReturn(Connection.TRANSACTION_READ_COMMITTED);
	given(con.getAutoCommit()).willReturn(true);

	TransactionTemplate tt = new TransactionTemplate(tm);
	tt.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRES_NEW);
	tt.setIsolationLevel(TransactionDefinition.ISOLATION_SERIALIZABLE);
	tt.setReadOnly(true);
	assertTrue("Hasn't thread connection", !TransactionSynchronizationManager.hasResource(ds));
	tt.execute(new TransactionCallbackWithoutResult() {
		@Override
		protected void doInTransactionWithoutResult(TransactionStatus status) {
			assertTrue(TransactionSynchronizationManager.isCurrentTransactionReadOnly());
			assertTrue(TransactionSynchronizationManager.isActualTransactionActive());
			// something transactional
		}
	});

	assertTrue("Hasn't thread connection", !TransactionSynchronizationManager.hasResource(ds));
	InOrder ordered = inOrder(con);
	ordered.verify(con).setTransactionIsolation(Connection.TRANSACTION_SERIALIZABLE);
	ordered.verify(con).setAutoCommit(false);
	ordered.verify(con).commit();
	ordered.verify(con).setAutoCommit(true);
	ordered.verify(con).setTransactionIsolation(Connection.TRANSACTION_READ_COMMITTED);
	verify(con).close();
}
 
Example 6
Source File: AbstractTestDAO.java    From yes-cart with Apache License 2.0 5 votes vote down vote up
@Before
public void setUp()   {
    checkEnabledDumps();
    transactionManager =   ctx().getBean("transactionManager", PlatformTransactionManager.class);
    tx = new TransactionTemplate(transactionManager);
    txReadOnly = new TransactionTemplate(transactionManager);
    txReadOnly.setReadOnly(true);
}
 
Example 7
Source File: IndexBuilderLuceneHibernateTxAwareImpl.java    From yes-cart with Apache License 2.0 5 votes vote down vote up
/** {@inheritDoc} */
@Override
protected Object startTx() {
    TransactionTemplate tx = new TransactionTemplate(this.platformTransactionManager);
    tx.setReadOnly(true);
    return this.platformTransactionManager.getTransaction(tx);
}
 
Example 8
Source File: DataSourceTransactionManagerTests.java    From effectivejava with Apache License 2.0 5 votes vote down vote up
@Test
public void testTransactionWithIsolationAndReadOnly() throws Exception {
	given(con.getTransactionIsolation()).willReturn(Connection.TRANSACTION_READ_COMMITTED);
	given(con.getAutoCommit()).willReturn(true);

	TransactionTemplate tt = new TransactionTemplate(tm);
	tt.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRES_NEW);
	tt.setIsolationLevel(TransactionDefinition.ISOLATION_SERIALIZABLE);
	tt.setReadOnly(true);
	assertTrue("Hasn't thread connection", !TransactionSynchronizationManager.hasResource(ds));
	tt.execute(new TransactionCallbackWithoutResult() {
		@Override
		protected void doInTransactionWithoutResult(TransactionStatus status) {
			assertTrue(TransactionSynchronizationManager.isCurrentTransactionReadOnly());
			assertTrue(TransactionSynchronizationManager.isActualTransactionActive());
			// something transactional
		}
	});

	assertTrue("Hasn't thread connection", !TransactionSynchronizationManager.hasResource(ds));
	InOrder ordered = inOrder(con);
	ordered.verify(con).setTransactionIsolation(Connection.TRANSACTION_SERIALIZABLE);
	ordered.verify(con).setAutoCommit(false);
	ordered.verify(con).commit();
	ordered.verify(con).setAutoCommit(true);
	ordered.verify(con).setTransactionIsolation(Connection.TRANSACTION_READ_COMMITTED);
	verify(con).close();
}
 
Example 9
Source File: MolgenisInterceptor.java    From molgenis with GNU Lesser General Public License v3.0 5 votes vote down vote up
@Override
public void postHandle(
    HttpServletRequest request,
    HttpServletResponse response,
    Object handler,
    ModelAndView modelAndView) {
  if (modelAndView != null) {
    String viewName = modelAndView.getViewName();
    if (viewName == null || !viewName.startsWith("forward:")) {
      // use programmatic transaction instead of transaction annotation since we only want to
      // start a read-only transaction when a modelAndView exists
      TransactionTemplate transactionTemplate = new TransactionTemplate(transactionManager);
      transactionTemplate.setReadOnly(true);
      transactionTemplate.execute(
          status -> {
            modelAndView.addObject(
                KEY_RESOURCE_FINGERPRINT_REGISTRY, resourceFingerprintRegistry);
            modelAndView.addObject(KEY_THEME_FINGERPRINT_REGISTRY, themeFingerprintRegistry);
            modelAndView.addObject(KEY_APP_SETTINGS, createAppSettings());
            modelAndView.addObject(
                KEY_AUTHENTICATION_OIDC_CLIENTS, runAsSystem(this::getOidcClients));
            modelAndView.addObject(
                KEY_AUTHENTICATION_SIGN_UP, authenticationSettings.getSignUp());
            modelAndView.addObject(KEY_ENVIRONMENT, getEnvironmentAttributes());
            modelAndView.addObject(
                KEY_I18N,
                new MessageSourceResourceBundle(messageSource, LocaleContextHolder.getLocale()));
            modelAndView.addObject(KEY_GSON, gson);
            modelAndView.addObject(KEY_LANGUAGE, LocaleContextHolder.getLocale().getLanguage());
            modelAndView.addObject(KEY_FALLBACK_LANGUAGE, appSettings.getLanguageCode());
            modelAndView.addObject(
                KEY_SUPER_USER, userAccountService.getCurrentUser().isSuperuser());
            return null;
          });
    }
  }
}
 
Example 10
Source File: HibernateJtaTransactionTests.java    From spring4-understanding with Apache License 2.0 4 votes vote down vote up
@SuppressWarnings({ "rawtypes", "unchecked" })
protected void doTestJtaTransactionCommitWithPreBound(boolean jtaTm, final boolean flushNever,
		final boolean readOnly) throws Exception {


	UserTransaction ut = mock(UserTransaction.class);
	given(ut.getStatus()).willReturn(Status.STATUS_NO_TRANSACTION,
			Status.STATUS_ACTIVE, Status.STATUS_ACTIVE);

	TransactionManager tm = mock(TransactionManager.class);
	if (jtaTm) {
		MockJtaTransaction transaction = new MockJtaTransaction();
		given(tm.getTransaction()).willReturn(transaction);
	}

	final SessionFactoryImplementor sf = mock(SessionFactoryImplementor.class);
	final ExtendedSession session = mock(ExtendedSession.class);
	given(sf.getTransactionManager()).willReturn(jtaTm ? tm : null);
	given(session.isOpen()).willReturn(true);
	given(session.getFlushMode()).willReturn(flushNever ? FlushMode.MANUAL: FlushMode.AUTO);

	TransactionSynchronizationManager.bindResource(sf, new SessionHolder(session));
	try {
		JtaTransactionManager ptm = new JtaTransactionManager(ut);
		TransactionTemplate tt = new TransactionTemplate(ptm);
		tt.setReadOnly(readOnly);
		final List l = new ArrayList();
		l.add("test");
		assertTrue("JTA synchronizations not active", !TransactionSynchronizationManager.isSynchronizationActive());
		assertTrue("Has thread session", TransactionSynchronizationManager.hasResource(sf));

		Object result = tt.execute(new TransactionCallback() {

			@Override
			public Object doInTransaction(TransactionStatus status) {
				try {
					assertTrue("JTA synchronizations active",
						TransactionSynchronizationManager.isSynchronizationActive());
					assertTrue("Has thread session", TransactionSynchronizationManager.hasResource(sf));
					HibernateTemplate ht = new HibernateTemplate(sf);
					ht.setExposeNativeSession(true);
					List htl = null;
					for (int i = 0; i < 5; i++) {
						htl = ht.executeFind(new HibernateCallback() {

							@Override
							public Object doInHibernate(org.hibernate.Session sess) {
								assertTrue("Has thread session", TransactionSynchronizationManager.hasResource(sf));
								assertEquals(session, sess);
								return l;
							}
						});
						assertTrue("Has thread session", TransactionSynchronizationManager.hasResource(sf));
					}
					return htl;
				}
				catch (Error err) {
					err.printStackTrace();
					throw err;
				}
			}
		});

		assertTrue("Correct result list", result == l);
		assertTrue("Has thread session", TransactionSynchronizationManager.hasResource(sf));
		assertTrue("JTA synchronizations not active", !TransactionSynchronizationManager.isSynchronizationActive());
	}
	finally {
		TransactionSynchronizationManager.unbindResource(sf);
	}

	verify(ut).begin();
	verify(ut).commit();

	if (flushNever) {
		if(!readOnly) {
			InOrder ordered = inOrder(session);
			ordered.verify(session).setFlushMode(FlushMode.AUTO);
			ordered.verify(session).setFlushMode(FlushMode.MANUAL);
		}
	}
	if(!flushNever && !readOnly) {
		verify(session).flush();
	}
	verify(session).afterTransactionCompletion(true, null);
	verify(session).disconnect();
}
 
Example 11
Source File: HibernateTransactionManagerTests.java    From spring4-understanding with Apache License 2.0 4 votes vote down vote up
@Test
public void testTransactionCommitWithReadOnly() throws Exception {
	Connection con = mock(Connection.class);
	final SessionFactory sf = mock(SessionFactory.class);
	Session session = mock(Session.class);
	Transaction tx = mock(Transaction.class);
	Query query = mock(Query.class);

	final List list = new ArrayList();
	list.add("test");
	given(sf.openSession()).willReturn(session);
	given(session.beginTransaction()).willReturn(tx);
	given(session.connection()).willReturn(con);
	given(session.isOpen()).willReturn(true);
	given(session.createQuery("some query string")).willReturn(query);
	given(query.list()).willReturn(list);
	given(session.isConnected()).willReturn(true);
	given(con.isReadOnly()).willReturn(true);

	HibernateTransactionManager tm = new HibernateTransactionManager(sf);
	TransactionTemplate tt = new TransactionTemplate(tm);
	tt.setReadOnly(true);
	assertTrue("Hasn't thread session", !TransactionSynchronizationManager.hasResource(sf));
	assertTrue("JTA synchronizations not active", !TransactionSynchronizationManager.isSynchronizationActive());

	Object result = tt.execute(new TransactionCallback() {
		@Override
		public Object doInTransaction(TransactionStatus status) {
			assertTrue("Has thread session", TransactionSynchronizationManager.hasResource(sf));
			assertTrue(TransactionSynchronizationManager.isCurrentTransactionReadOnly());
			assertTrue(TransactionSynchronizationManager.isActualTransactionActive());
			HibernateTemplate ht = new HibernateTemplate(sf);
			return ht.find("some query string");
		}
	});
	assertTrue("Correct result list", result == list);

	assertTrue("Hasn't thread session", !TransactionSynchronizationManager.hasResource(sf));
	assertTrue("JTA synchronizations not active", !TransactionSynchronizationManager.isSynchronizationActive());

	verify(session).setFlushMode(FlushMode.MANUAL);
	verify(con).setReadOnly(true);
	verify(tx).commit();
	verify(con).setReadOnly(false);
	verify(session).close();
}
 
Example 12
Source File: TransactionalRepositoryDecorator.java    From molgenis with GNU Lesser General Public License v3.0 4 votes vote down vote up
private TransactionTemplate createReadonlyTransactionTemplate() {
  TransactionTemplate transactionTemplate = new TransactionTemplate(transactionManager);
  transactionTemplate.setReadOnly(true);
  return transactionTemplate;
}
 
Example 13
Source File: NextServerUserDetailsService.java    From nextreports-server with Apache License 2.0 4 votes vote down vote up
public void afterPropertiesSet() throws Exception {
	transactionTemplate = new TransactionTemplate(transactionManager);
	transactionTemplate.setReadOnly(true);
}