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

The following examples show how to use org.springframework.transaction.support.TransactionTemplate#execute() . 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: TransactionSupportTests.java    From spring4-understanding with Apache License 2.0 6 votes vote down vote up
@Test
public void transactionTemplateWithError() {
	TestTransactionManager tm = new TestTransactionManager(false, true);
	TransactionTemplate template = new TransactionTemplate(tm);
	try {
		template.execute(new TransactionCallbackWithoutResult() {
			@Override
			protected void doInTransactionWithoutResult(TransactionStatus status) {
				throw new Error("Some application error");
			}
		});
		fail("Should have propagated Error");
	}
	catch (Error err) {
		// expected
		assertTrue("triggered begin", tm.begin);
		assertTrue("no commit", !tm.commit);
		assertTrue("triggered rollback", tm.rollback);
		assertTrue("no rollbackOnly", !tm.rollbackOnly);
	}
}
 
Example 2
Source File: JtaTransactionManagerTests.java    From spring-analysis-note with MIT License 6 votes vote down vote up
@Test
public void jtaTransactionManagerWithPropagationNotSupported() throws Exception {
	UserTransaction ut = mock(UserTransaction.class);
	TransactionManager tm = mock(TransactionManager.class);
	Transaction tx = mock(Transaction.class);
	given(ut.getStatus()).willReturn(Status.STATUS_ACTIVE);
	given(tm.suspend()).willReturn(tx);

	JtaTransactionManager ptm = newJtaTransactionManager(ut, tm);
	TransactionTemplate tt = new TransactionTemplate(ptm);
	tt.setPropagationBehavior(TransactionDefinition.PROPAGATION_NOT_SUPPORTED);
	assertFalse(TransactionSynchronizationManager.isSynchronizationActive());
	tt.execute(new TransactionCallbackWithoutResult() {
		@Override
		protected void doInTransactionWithoutResult(TransactionStatus status) {
			assertTrue(TransactionSynchronizationManager.isSynchronizationActive());
			status.setRollbackOnly();
		}
	});
	assertFalse(TransactionSynchronizationManager.isSynchronizationActive());

	verify(tm).resume(tx);
}
 
Example 3
Source File: AdminReservationRequestManager.java    From alf.io with GNU General Public License v3.0 6 votes vote down vote up
private Result<Triple<TicketReservation, List<Ticket>, Event>> processReservation(AdminReservationRequest request, Event event, User user) {
    DefaultTransactionDefinition definition = new DefaultTransactionDefinition(TransactionDefinition.PROPAGATION_NESTED);
    TransactionTemplate template = new TransactionTemplate(transactionManager, definition);
    return template.execute(status -> {
        var savepoint = status.createSavepoint();
        try {
            String eventName = event.getShortName();
            String username = user.getUsername();
            Result<Triple<TicketReservation, List<Ticket>, Event>> result = adminReservationManager.createReservation(request.getBody(), eventName, username)
                .flatMap(r -> adminReservationManager.confirmReservation(eventName, r.getLeft().getId(), username, orEmpty(request.getBody().getNotification())));
            if(!result.isSuccess()) {
                status.rollbackToSavepoint(savepoint);
            }
            return result;
        } catch(Exception ex) {
            status.rollbackToSavepoint(savepoint);
            return Result.error(singletonList(ErrorCode.custom("", ex.getMessage())));
        }
    });
}
 
Example 4
Source File: JtaTransactionManagerTests.java    From spring4-understanding with Apache License 2.0 6 votes vote down vote up
@Test
public void jtaTransactionManagerWithPropagationRequiresNewAndSuspensionNotSupported() throws Exception {
	UserTransaction ut = mock(UserTransaction.class);
	given(ut.getStatus()).willReturn(Status.STATUS_ACTIVE);

	JtaTransactionManager ptm = newJtaTransactionManager(ut);
	TransactionTemplate tt = new TransactionTemplate(ptm);
	tt.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRES_NEW);
	assertFalse(TransactionSynchronizationManager.isSynchronizationActive());
	try {
		tt.execute(new TransactionCallbackWithoutResult() {
			@Override
			protected void doInTransactionWithoutResult(TransactionStatus status) {
			}
		});
		fail("Should have thrown TransactionSuspensionNotSupportedException");
	}
	catch (TransactionSuspensionNotSupportedException ex) {
		// expected
	}
	assertFalse(TransactionSynchronizationManager.isSynchronizationActive());
}
 
Example 5
Source File: JtaTransactionManagerTests.java    From spring4-understanding with Apache License 2.0 6 votes vote down vote up
@Test
public void jtaTransactionManagerWithExistingAndPropagationSupports() throws Exception {
	UserTransaction ut = mock(UserTransaction.class);
	given(ut.getStatus()).willReturn(Status.STATUS_ACTIVE);

	final TransactionSynchronization synch = mock(TransactionSynchronization.class);

	JtaTransactionManager ptm = newJtaTransactionManager(ut);
	TransactionTemplate tt = new TransactionTemplate(ptm);
	tt.setPropagationBehavior(TransactionDefinition.PROPAGATION_SUPPORTS);
	assertFalse(TransactionSynchronizationManager.isSynchronizationActive());
	tt.execute(new TransactionCallbackWithoutResult() {
		@Override
		protected void doInTransactionWithoutResult(TransactionStatus status) {
			assertTrue(TransactionSynchronizationManager.isSynchronizationActive());
			TransactionSynchronizationManager.registerSynchronization(synch);
			status.setRollbackOnly();
		}
	});
	assertFalse(TransactionSynchronizationManager.isSynchronizationActive());

	verify(ut).setRollbackOnly();
	verify(synch).beforeCompletion();
	verify(synch).afterCompletion(TransactionSynchronization.STATUS_UNKNOWN);
}
 
Example 6
Source File: JtaTransactionManagerTests.java    From spring-analysis-note with MIT License 6 votes vote down vote up
@Test
public void jtaTransactionManagerWithExistingAndPropagationSupports() throws Exception {
	UserTransaction ut = mock(UserTransaction.class);
	given(ut.getStatus()).willReturn(Status.STATUS_ACTIVE);

	final TransactionSynchronization synch = mock(TransactionSynchronization.class);

	JtaTransactionManager ptm = newJtaTransactionManager(ut);
	TransactionTemplate tt = new TransactionTemplate(ptm);
	tt.setPropagationBehavior(TransactionDefinition.PROPAGATION_SUPPORTS);
	assertFalse(TransactionSynchronizationManager.isSynchronizationActive());
	tt.execute(new TransactionCallbackWithoutResult() {
		@Override
		protected void doInTransactionWithoutResult(TransactionStatus status) {
			assertTrue(TransactionSynchronizationManager.isSynchronizationActive());
			TransactionSynchronizationManager.registerSynchronization(synch);
			status.setRollbackOnly();
		}
	});
	assertFalse(TransactionSynchronizationManager.isSynchronizationActive());

	verify(ut).setRollbackOnly();
	verify(synch).beforeCompletion();
	verify(synch).afterCompletion(TransactionSynchronization.STATUS_UNKNOWN);
}
 
Example 7
Source File: TransactionSupportTests.java    From spring-analysis-note with MIT License 6 votes vote down vote up
@Test
public void transactionTemplateWithException() {
	TestTransactionManager tm = new TestTransactionManager(false, true);
	TransactionTemplate template = new TransactionTemplate(tm);
	final RuntimeException ex = new RuntimeException("Some application exception");
	try {
		template.execute(new TransactionCallbackWithoutResult() {
			@Override
			protected void doInTransactionWithoutResult(TransactionStatus status) {
				throw ex;
			}
		});
		fail("Should have propagated RuntimeException");
	}
	catch (RuntimeException caught) {
		// expected
		assertTrue("Correct exception", caught == ex);
		assertTrue("triggered begin", tm.begin);
		assertTrue("no commit", !tm.commit);
		assertTrue("triggered rollback", tm.rollback);
		assertTrue("no rollbackOnly", !tm.rollbackOnly);
	}
}
 
Example 8
Source File: CciLocalTransactionTests.java    From spring4-understanding with Apache License 2.0 5 votes vote down vote up
/**
 * Test if a transaction ( begin / commit ) is executed on the
 * LocalTransaction when CciLocalTransactionManager is specified as
 * transaction manager.
 */
@Test
public void testLocalTransactionCommit() throws ResourceException {
	final ConnectionFactory connectionFactory = mock(ConnectionFactory.class);
	Connection connection = mock(Connection.class);
	Interaction interaction = mock(Interaction.class);
	LocalTransaction localTransaction = mock(LocalTransaction.class);
	final Record record = mock(Record.class);
	final InteractionSpec interactionSpec = mock(InteractionSpec.class);

	given(connectionFactory.getConnection()).willReturn(connection);
	given(connection.getLocalTransaction()).willReturn(localTransaction);
	given(connection.createInteraction()).willReturn(interaction);
	given(interaction.execute(interactionSpec, record, record)).willReturn(true);
	given(connection.getLocalTransaction()).willReturn(localTransaction);

	CciLocalTransactionManager tm = new CciLocalTransactionManager();
	tm.setConnectionFactory(connectionFactory);
	TransactionTemplate tt = new TransactionTemplate(tm);

	tt.execute(new TransactionCallbackWithoutResult() {
		@Override
		protected void doInTransactionWithoutResult(TransactionStatus status) {
			assertTrue("Has thread connection", TransactionSynchronizationManager.hasResource(connectionFactory));
			CciTemplate ct = new CciTemplate(connectionFactory);
			ct.execute(interactionSpec, record, record);
		}
	});

	verify(localTransaction).begin();
	verify(interaction).close();
	verify(localTransaction).commit();
	verify(connection).close();
}
 
Example 9
Source File: ExampleUsingMultipleTransactionManagerTest.java    From sdn-rx with Apache License 2.0 5 votes vote down vote up
/**
 * The test here already runs {@link org.springframework.transaction.annotation.Transactional} and thus
 * uses the default transaction manager (the one configured for the movies db).
 * <p>We inject one for "otherDb" as well for creating a transaction template and do some additional work.
 *
 * @param client
 * @param transactionManagerForOtherDb
 */
@Test
void storeNewPersonShouldUseTheCorrectDatabase(
	@Autowired Neo4jClient client,
	@Autowired @Qualifier("transactionManagerForOtherDb") PlatformTransactionManager transactionManagerForOtherDb
) {
	PersonEntity personEntity = new PersonEntity(1929, "Carlo Pedersoli");
	repositoryUnderTest.save(personEntity).getName();

	// Verify with the client, for reasoning have a look at ExampleUsingStaticDatabaseNameTest
	Optional<String> name = client
		.query("MATCH (p:Person) RETURN p.name")
		.in("movies")
		.fetchAs(String.class).one();
	assertThat(name).hasValue(personEntity.getName());

	// Build the new transaction template. That would typically be a bean.
	// As we are gonna used that inside an ongoing transaction and the ongoing transaction
	// is already tied to a database, we must spawn a new one with PROPAGATION_REQUIRES_NEW
	TransactionTemplate transactionTemplate = new TransactionTemplate(transactionManagerForOtherDb);
	transactionTemplate.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRES_NEW);
	name = transactionTemplate.execute(t -> client
		.query("MATCH (p:Person) RETURN p.name")
		.in("otherDb")
		.fetchAs(String.class).one());
	assertThat(name).isEmpty();
}
 
Example 10
Source File: DataSourceTransactionManagerTests.java    From spring4-understanding with Apache License 2.0 5 votes vote down vote up
@Test public void testTransactionWithPropagationNotSupported() throws Exception {
	TransactionTemplate tt = new TransactionTemplate(tm);
	tt.setPropagationBehavior(TransactionDefinition.PROPAGATION_NOT_SUPPORTED);
	assertTrue("Hasn't thread connection", !TransactionSynchronizationManager.hasResource(ds));

	tt.execute(new TransactionCallbackWithoutResult() {
		@Override
		protected void doInTransactionWithoutResult(TransactionStatus status) throws RuntimeException {
			assertTrue("Hasn't thread connection", !TransactionSynchronizationManager.hasResource(ds));
			assertTrue("Is not new transaction", !status.isNewTransaction());
		}
	});

	assertTrue("Hasn't thread connection", !TransactionSynchronizationManager.hasResource(ds));
}
 
Example 11
Source File: JndiJtaTransactionManagerTests.java    From spring-analysis-note with MIT License 5 votes vote down vote up
@Test
public void jtaTransactionManagerWithCustomJndiLookups() 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);

	JtaTransactionManager ptm = new JtaTransactionManager();
	ptm.setUserTransactionName("jndi-ut");
	ptm.setTransactionManagerName("jndi-tm");
	ExpectedLookupTemplate jndiTemplate = new ExpectedLookupTemplate();
	jndiTemplate.addObject("jndi-ut", ut);
	jndiTemplate.addObject("jndi-tm", tm);
	ptm.setJndiTemplate(jndiTemplate);
	ptm.afterPropertiesSet();

	assertEquals(ut, ptm.getUserTransaction());
	assertEquals(tm, ptm.getTransactionManager());

	TransactionTemplate tt = new TransactionTemplate(ptm);
	assertTrue(!TransactionSynchronizationManager.isSynchronizationActive());
	assertFalse(TransactionSynchronizationManager.isCurrentTransactionReadOnly());
	tt.execute(new TransactionCallbackWithoutResult() {
		@Override
		protected void doInTransactionWithoutResult(TransactionStatus status) {
			// something transactional
			assertTrue(TransactionSynchronizationManager.isSynchronizationActive());
			assertFalse(TransactionSynchronizationManager.isCurrentTransactionReadOnly());
		}
	});
	assertTrue(!TransactionSynchronizationManager.isSynchronizationActive());
	assertFalse(TransactionSynchronizationManager.isCurrentTransactionReadOnly());

	verify(ut).begin();
	verify(ut).commit();
}
 
Example 12
Source File: HelpManagerImpl.java    From sakai with Educational Community License v2.0 5 votes vote down vote up
private void dropExistingContent() {
	if (log.isDebugEnabled()) {
		log.debug("dropExistingContent()");
	}

	TransactionTemplate tt = new TransactionTemplate(txManager);
	tt.execute(new TransactionCallback() {
		public Object doInTransaction(TransactionStatus status) {
			getHibernateTemplate().bulkUpdate("delete CategoryBean");
			getHibernateTemplate().flush();
			return null;
		}
	});
}
 
Example 13
Source File: FriendIgnoreBullhornHandler.java    From sakai with Educational Community License v2.0 5 votes vote down vote up
@Override
public Optional<List<BullhornData>> handleEvent(Event e, Cache<String, Long> countCache) {

    String from = e.getUserId();

    String ref = e.getResource();
    String[] pathParts = ref.split("/");

    String to = pathParts[2];
    try {
        TransactionTemplate transactionTemplate = new TransactionTemplate(transactionManager);

        transactionTemplate.execute(new TransactionCallbackWithoutResult() {

            protected void doInTransactionWithoutResult(TransactionStatus status) {

                sessionFactory.getCurrentSession().createQuery("delete BullhornAlert where event = :event and fromUser = :fromUser")
                    .setString("event", ProfileConstants.EVENT_FRIEND_REQUEST)
                    .setString("fromUser", to).executeUpdate();
            }
        });
    } catch (Exception e1) {
        log.error("Failed to delete bullhorn request event", e1);
    }
    countCache.remove(from);
    return Optional.empty();
}
 
Example 14
Source File: JtaTransactionManagerTests.java    From java-technology-stack with MIT License 5 votes vote down vote up
@Test
public void jtaTransactionManagerWithExistingTransactionAndException() throws Exception {
	UserTransaction ut = mock(UserTransaction.class);
	given(ut.getStatus()).willReturn(Status.STATUS_ACTIVE);

	final TransactionSynchronization synch = mock(TransactionSynchronization.class);

	JtaTransactionManager ptm = newJtaTransactionManager(ut);
	TransactionTemplate tt = new TransactionTemplate(ptm);
	assertFalse(TransactionSynchronizationManager.isSynchronizationActive());
	try {
		tt.execute(new TransactionCallbackWithoutResult() {
			@Override
			protected void doInTransactionWithoutResult(TransactionStatus status) {
				assertTrue(TransactionSynchronizationManager.isSynchronizationActive());
				TransactionSynchronizationManager.registerSynchronization(synch);
				throw new IllegalStateException("I want a rollback");
			}
		});
		fail("Should have thrown IllegalStateException");
	}
	catch (IllegalStateException ex) {
		// expected
	}
	assertFalse(TransactionSynchronizationManager.isSynchronizationActive());

	verify(ut).setRollbackOnly();
	verify(synch).beforeCompletion();
	verify(synch).afterCompletion(TransactionSynchronization.STATUS_UNKNOWN);
}
 
Example 15
Source File: DataSourceTransactionManagerTests.java    From effectivejava with Apache License 2.0 5 votes vote down vote up
@Test
public void testTransactionAwareDataSourceProxy() throws Exception {
	given(con.getAutoCommit()).willReturn(true);

	TransactionTemplate tt = new TransactionTemplate(tm);
	assertTrue("Hasn't thread connection", !TransactionSynchronizationManager.hasResource(ds));
	tt.execute(new TransactionCallbackWithoutResult() {
		@Override
		protected void doInTransactionWithoutResult(TransactionStatus status) {
			// something transactional
			assertEquals(con, DataSourceUtils.getConnection(ds));
			TransactionAwareDataSourceProxy dsProxy = new TransactionAwareDataSourceProxy(ds);
			try {
				assertEquals(con, ((ConnectionProxy) dsProxy.getConnection()).getTargetConnection());
				assertEquals(con, new SimpleNativeJdbcExtractor().getNativeConnection(dsProxy.getConnection()));
				// should be ignored
				dsProxy.getConnection().close();
			}
			catch (SQLException ex) {
				throw new UncategorizedSQLException("", "", ex);
			}
		}
	});

	assertTrue("Hasn't thread connection", !TransactionSynchronizationManager.hasResource(ds));
	InOrder ordered = inOrder(con);
	ordered.verify(con).setAutoCommit(false);
	ordered.verify(con).commit();
	ordered.verify(con).setAutoCommit(true);
	verify(con).close();
}
 
Example 16
Source File: JdbcAuditor.java    From nextreports-server with Apache License 2.0 5 votes vote down vote up
public void logEvent(final AuditEvent event) {
	TransactionTemplate transactionTemplate = new TransactionTemplate();
    transactionTemplate.setTransactionManager(new DataSourceTransactionManager(getDataSource()));
    transactionTemplate.execute(new TransactionCallbackWithoutResult() {
    	
    	@Override
           protected void doInTransactionWithoutResult(TransactionStatus status) {
       	    int id = getNextEventId();

       		Object[] eventData = new Object[8];
       	    eventData[0] = id;
       		eventData[1] = event.getDate();
       		eventData[2] = event.getUsername();
       		eventData[3] = event.getAction();
       		eventData[4] = event.getSession();
       		eventData[5] = event.getIp();
       		eventData[6] = event.getLevel();
       		eventData[7] = event.getErrorMessage();
       		
       	    getJdbcTemplate().update(INSERT_EVENT_SQL, eventData);
       	    
       	    Map<String, Object> context = event.getContext();
       	    for (String name : context.keySet()) {
           		Object[] contextData = new Object[3];
           		contextData[0] = id;
           		contextData[1] = name;
           		contextData[2] = context.get(name);

       	    	getJdbcTemplate().update(INSERT_CONTEXT_SQL, contextData);
       	    }
           }
           
    });
}
 
Example 17
Source File: JndiJtaTransactionManagerTests.java    From java-technology-stack with MIT License 5 votes vote down vote up
@Test
public void jtaTransactionManagerWithCustomJndiLookups() 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);

	JtaTransactionManager ptm = new JtaTransactionManager();
	ptm.setUserTransactionName("jndi-ut");
	ptm.setTransactionManagerName("jndi-tm");
	ExpectedLookupTemplate jndiTemplate = new ExpectedLookupTemplate();
	jndiTemplate.addObject("jndi-ut", ut);
	jndiTemplate.addObject("jndi-tm", tm);
	ptm.setJndiTemplate(jndiTemplate);
	ptm.afterPropertiesSet();

	assertEquals(ut, ptm.getUserTransaction());
	assertEquals(tm, ptm.getTransactionManager());

	TransactionTemplate tt = new TransactionTemplate(ptm);
	assertTrue(!TransactionSynchronizationManager.isSynchronizationActive());
	assertFalse(TransactionSynchronizationManager.isCurrentTransactionReadOnly());
	tt.execute(new TransactionCallbackWithoutResult() {
		@Override
		protected void doInTransactionWithoutResult(TransactionStatus status) {
			// something transactional
			assertTrue(TransactionSynchronizationManager.isSynchronizationActive());
			assertFalse(TransactionSynchronizationManager.isCurrentTransactionReadOnly());
		}
	});
	assertTrue(!TransactionSynchronizationManager.isSynchronizationActive());
	assertFalse(TransactionSynchronizationManager.isCurrentTransactionReadOnly());

	verify(ut).begin();
	verify(ut).commit();
}
 
Example 18
Source File: JdoTransactionManagerTests.java    From spring4-understanding with Apache License 2.0 5 votes vote down vote up
@Test
public void testTransactionRollbackWithAlreadyRolledBack() {
	given(pmf.getPersistenceManager()).willReturn(pm);
	given(pm.currentTransaction()).willReturn(tx);

	PlatformTransactionManager tm = new JdoTransactionManager(pmf);
	TransactionTemplate tt = new TransactionTemplate(tm);
	assertTrue("Hasn't thread pm", !TransactionSynchronizationManager.hasResource(pmf));
	assertTrue("JTA synchronizations not active", !TransactionSynchronizationManager.isSynchronizationActive());

	try {
		tt.execute(new TransactionCallback() {
			@Override
			public Object doInTransaction(TransactionStatus status) {
				assertTrue("Has thread pm", TransactionSynchronizationManager.hasResource(pmf));
				PersistenceManagerFactoryUtils.getPersistenceManager(pmf, true);
				throw new RuntimeException("application exception");
			}
		});
		fail("Should have thrown RuntimeException");
	}
	catch (RuntimeException ex) {
		// expected
	}

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

	verify(pm).close();
	verify(tx).begin();
}
 
Example 19
Source File: DataSourceTransactionManagerTests.java    From effectivejava with Apache License 2.0 4 votes vote down vote up
private void doTestTransactionCommitRestoringAutoCommit(
		boolean autoCommit, boolean lazyConnection, final boolean createStatement)
		throws Exception {
	if (lazyConnection) {
		given(con.getAutoCommit()).willReturn(autoCommit);
		given(con.getTransactionIsolation()).willReturn(Connection.TRANSACTION_READ_COMMITTED);
	}

	if (!lazyConnection || createStatement) {
		given(con.getAutoCommit()).willReturn(autoCommit);
	}

	final DataSource dsToUse = (lazyConnection ? new LazyConnectionDataSourceProxy(ds) : ds);
	tm = new DataSourceTransactionManager(dsToUse);
	TransactionTemplate tt = new TransactionTemplate(tm);
	assertTrue("Hasn't thread connection", !TransactionSynchronizationManager.hasResource(dsToUse));
	assertTrue("Synchronization not active", !TransactionSynchronizationManager.isSynchronizationActive());

	tt.execute(new TransactionCallbackWithoutResult() {
		@Override
		protected void doInTransactionWithoutResult(TransactionStatus status) throws RuntimeException {
			assertTrue("Has thread connection", TransactionSynchronizationManager.hasResource(dsToUse));
			assertTrue("Synchronization active", TransactionSynchronizationManager.isSynchronizationActive());
			assertTrue("Is new transaction", status.isNewTransaction());
			assertFalse(TransactionSynchronizationManager.isCurrentTransactionReadOnly());
			assertTrue(TransactionSynchronizationManager.isActualTransactionActive());
			Connection tCon = DataSourceUtils.getConnection(dsToUse);
			try {
				if (createStatement) {
					tCon.createStatement();
					assertEquals(con, new SimpleNativeJdbcExtractor().getNativeConnection(tCon));
				}
			}
			catch (SQLException ex) {
				throw new UncategorizedSQLException("", "", ex);
			}
		}
	});

	assertTrue("Hasn't thread connection", !TransactionSynchronizationManager.hasResource(dsToUse));
	assertTrue("Synchronization not active", !TransactionSynchronizationManager.isSynchronizationActive());

	if(autoCommit && (!lazyConnection || createStatement)) {
		InOrder ordered = inOrder(con);
		ordered.verify(con).setAutoCommit(false);
		ordered.verify(con).commit();
		ordered.verify(con).setAutoCommit(true);
	}
	if (createStatement) {
		verify(con, times(2)).close();
	}
	else {
		verify(con).close();
	}
}
 
Example 20
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();
}