org.springframework.jdbc.support.SQLStateSQLExceptionTranslator Java Examples

The following examples show how to use org.springframework.jdbc.support.SQLStateSQLExceptionTranslator. 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: RowMapperTests.java    From effectivejava with Apache License 2.0 6 votes vote down vote up
@Override
@Before
public void setUp() throws SQLException {
	connection = mock(Connection.class);
	statement = mock(Statement.class);
	preparedStatement = mock(PreparedStatement.class);
	resultSet = mock(ResultSet.class);
	given(connection.createStatement()).willReturn(statement);
	given(connection.prepareStatement(anyString())).willReturn(preparedStatement);
	given(statement.executeQuery(anyString())).willReturn(resultSet);
	given(preparedStatement.executeQuery()).willReturn(resultSet);
	given(resultSet.next()).willReturn(true, true, false);
	given(resultSet.getString(1)).willReturn("tb1", "tb2");
	given(resultSet.getInt(2)).willReturn(1, 2);
	template = new JdbcTemplate();
	template.setDataSource(new SingleConnectionDataSource(connection, false));
	template.setExceptionTranslator(new SQLStateSQLExceptionTranslator());
	template.afterPropertiesSet();
}
 
Example #2
Source File: JdbcTemplateTests.java    From spring-analysis-note with MIT License 6 votes vote down vote up
/**
 * Test that we see an SQLException translated using Error Code.
 * If we provide the SQLExceptionTranslator, we shouldn't use a connection
 * to get the metadata
 */
@Test
public void testUseCustomSQLErrorCodeTranslator() throws Exception {
	// Bad SQL state
	final SQLException sqlException = new SQLException("I have a known problem", "07000", 1054);
	final String sql = "SELECT ID FROM CUSTOMER";

	given(this.resultSet.next()).willReturn(true);
	given(this.connection.createStatement()).willReturn(this.preparedStatement);

	JdbcTemplate template = new JdbcTemplate();
	template.setDataSource(this.dataSource);
	// Set custom exception translator
	template.setExceptionTranslator(new SQLStateSQLExceptionTranslator());
	template.afterPropertiesSet();

	assertThatExceptionOfType(BadSqlGrammarException.class).isThrownBy(() ->
			template.query(sql, (RowCallbackHandler) rs -> {
				throw sqlException;
			}))
		.withCause(sqlException);
	verify(this.resultSet).close();
	verify(this.preparedStatement).close();
	verify(this.connection).close();
}
 
Example #3
Source File: AbstractRowMapperTests.java    From spring-analysis-note with MIT License 5 votes vote down vote up
@SuppressWarnings("unchecked")
public Mock(MockType type) throws Exception {
	connection = mock(Connection.class);
	statement = mock(Statement.class);
	resultSet = mock(ResultSet.class);
	resultSetMetaData = mock(ResultSetMetaData.class);

	given(connection.createStatement()).willReturn(statement);
	given(statement.executeQuery(anyString())).willReturn(resultSet);
	given(resultSet.getMetaData()).willReturn(resultSetMetaData);

	given(resultSet.next()).willReturn(true, false);
	given(resultSet.getString(1)).willReturn("Bubba");
	given(resultSet.getLong(2)).willReturn(22L);
	given(resultSet.getTimestamp(3)).willReturn(new Timestamp(1221222L));
	given(resultSet.getObject(anyInt(), any(Class.class))).willThrow(new SQLFeatureNotSupportedException());
	given(resultSet.getDate(3)).willReturn(new java.sql.Date(1221222L));
	given(resultSet.getBigDecimal(4)).willReturn(new BigDecimal("1234.56"));
	given(resultSet.wasNull()).willReturn(type == MockType.TWO);

	given(resultSetMetaData.getColumnCount()).willReturn(4);
	given(resultSetMetaData.getColumnLabel(1)).willReturn(
			type == MockType.THREE ? "Last Name" : "name");
	given(resultSetMetaData.getColumnLabel(2)).willReturn("age");
	given(resultSetMetaData.getColumnLabel(3)).willReturn("birth_date");
	given(resultSetMetaData.getColumnLabel(4)).willReturn("balance");

	jdbcTemplate = new JdbcTemplate();
	jdbcTemplate.setDataSource(new SingleConnectionDataSource(connection, false));
	jdbcTemplate.setExceptionTranslator(new SQLStateSQLExceptionTranslator());
	jdbcTemplate.afterPropertiesSet();
}
 
Example #4
Source File: JdbcTemplateTests.java    From effectivejava with Apache License 2.0 5 votes vote down vote up
/**
 * Test that we see an SQLException translated using Error Code.
 * If we provide the SQLExceptionTranslator, we shouldn't use a connection
 * to get the metadata
 */
@Test
public void testUseCustomSQLErrorCodeTranslator() throws Exception {
	// Bad SQL state
	final SQLException sqlException = new SQLException("I have a known problem", "07000", 1054);
	final String sql = "SELECT ID FROM CUSTOMER";

	given(this.resultSet.next()).willReturn(true);
	given(this.connection.createStatement()).willReturn(this.preparedStatement);

	JdbcTemplate template = new JdbcTemplate();
	template.setDataSource(this.dataSource);
	// Set custom exception translator
	template.setExceptionTranslator(new SQLStateSQLExceptionTranslator());
	template.afterPropertiesSet();

	this.thrown.expect(BadSqlGrammarException.class);
	this.thrown.expect(exceptionCause(sameInstance(sqlException)));
	try {
		template.query(sql, new RowCallbackHandler() {
			@Override
			public void processRow(ResultSet rs) throws SQLException {
				throw sqlException;
			}
		});
	}
	finally {
		verify(this.resultSet).close();
		verify(this.preparedStatement).close();
		verify(this.connection).close();
	}
}
 
Example #5
Source File: AbstractRowMapperTests.java    From effectivejava with Apache License 2.0 5 votes vote down vote up
public Mock(MockType type)
		throws Exception {
	connection = mock(Connection.class);
	statement = mock(Statement.class);
	resultSet = mock(ResultSet.class);
	resultSetMetaData = mock(ResultSetMetaData.class);

	given(connection.createStatement()).willReturn(statement);
	given(statement.executeQuery(anyString())).willReturn(resultSet);
	given(resultSet.getMetaData()).willReturn(resultSetMetaData);

	given(resultSet.next()).willReturn(true, false);
	given(resultSet.getString(1)).willReturn("Bubba");
	given(resultSet.getLong(2)).willReturn(22L);
	given(resultSet.getTimestamp(3)).willReturn(new Timestamp(1221222L));
	given(resultSet.getBigDecimal(4)).willReturn(new BigDecimal("1234.56"));
	given(resultSet.wasNull()).willReturn(type == MockType.TWO ? true : false);

	given(resultSetMetaData.getColumnCount()).willReturn(4);
	given(resultSetMetaData.getColumnLabel(1)).willReturn(
			type == MockType.THREE ? "Last Name" : "name");
	given(resultSetMetaData.getColumnLabel(2)).willReturn("age");
	given(resultSetMetaData.getColumnLabel(3)).willReturn("birth_date");
	given(resultSetMetaData.getColumnLabel(4)).willReturn("balance");

	jdbcTemplate = new JdbcTemplate();
	jdbcTemplate.setDataSource(new SingleConnectionDataSource(connection, false));
	jdbcTemplate.setExceptionTranslator(new SQLStateSQLExceptionTranslator());
	jdbcTemplate.afterPropertiesSet();
}
 
Example #6
Source File: StoredProcedureTests.java    From effectivejava with Apache License 2.0 5 votes vote down vote up
/**
 * Confirm no connection was used to get metadata. Does not use superclass replay
 * mechanism.
 *
 * @throws Exception
 */
@Test
public void testStoredProcedureConfiguredViaJdbcTemplateWithCustomExceptionTranslator()
		throws Exception {
	given(callableStatement.execute()).willReturn(false);
	given(callableStatement.getUpdateCount()).willReturn(-1);
	given(callableStatement.getObject(2)).willReturn(5);
	given(connection.prepareCall("{call " + StoredProcedureConfiguredViaJdbcTemplate.SQL + "(?, ?)}")
			).willReturn(callableStatement);

	class TestJdbcTemplate extends JdbcTemplate {

		int calls;

		@Override
		public Map<String, Object> call(CallableStatementCreator csc,
				List<SqlParameter> declaredParameters) throws DataAccessException {
			calls++;
			return super.call(csc, declaredParameters);
		}
	}
	TestJdbcTemplate t = new TestJdbcTemplate();
	t.setDataSource(dataSource);
	// Will fail without the following, because we're not able to get a connection
	// from the DataSource here if we need to to create an ExceptionTranslator
	t.setExceptionTranslator(new SQLStateSQLExceptionTranslator());
	StoredProcedureConfiguredViaJdbcTemplate sp = new StoredProcedureConfiguredViaJdbcTemplate(t);

	assertEquals(sp.execute(11), 5);
	assertEquals(1, t.calls);

	verify(callableStatement).setObject(1, 11, Types.INTEGER);
	verify(callableStatement).registerOutParameter(2, Types.INTEGER);
}
 
Example #7
Source File: RowMapperTests.java    From spring4-understanding with Apache License 2.0 5 votes vote down vote up
@Before
public void setUp() throws SQLException {
	given(connection.createStatement()).willReturn(statement);
	given(connection.prepareStatement(anyString())).willReturn(preparedStatement);
	given(statement.executeQuery(anyString())).willReturn(resultSet);
	given(preparedStatement.executeQuery()).willReturn(resultSet);
	given(resultSet.next()).willReturn(true, true, false);
	given(resultSet.getString(1)).willReturn("tb1", "tb2");
	given(resultSet.getInt(2)).willReturn(1, 2);

	template.setDataSource(new SingleConnectionDataSource(connection, false));
	template.setExceptionTranslator(new SQLStateSQLExceptionTranslator());
	template.afterPropertiesSet();
}
 
Example #8
Source File: JdbcTemplateTests.java    From spring4-understanding with Apache License 2.0 5 votes vote down vote up
/**
 * Test that we see an SQLException translated using Error Code.
 * If we provide the SQLExceptionTranslator, we shouldn't use a connection
 * to get the metadata
 */
@Test
public void testUseCustomSQLErrorCodeTranslator() throws Exception {
	// Bad SQL state
	final SQLException sqlException = new SQLException("I have a known problem", "07000", 1054);
	final String sql = "SELECT ID FROM CUSTOMER";

	given(this.resultSet.next()).willReturn(true);
	given(this.connection.createStatement()).willReturn(this.preparedStatement);

	JdbcTemplate template = new JdbcTemplate();
	template.setDataSource(this.dataSource);
	// Set custom exception translator
	template.setExceptionTranslator(new SQLStateSQLExceptionTranslator());
	template.afterPropertiesSet();

	this.thrown.expect(BadSqlGrammarException.class);
	this.thrown.expect(exceptionCause(sameInstance(sqlException)));
	try {
		template.query(sql, new RowCallbackHandler() {
			@Override
			public void processRow(ResultSet rs) throws SQLException {
				throw sqlException;
			}
		});
	}
	finally {
		verify(this.resultSet).close();
		verify(this.preparedStatement).close();
		verify(this.connection).close();
	}
}
 
Example #9
Source File: AbstractRowMapperTests.java    From spring4-understanding with Apache License 2.0 5 votes vote down vote up
public Mock(MockType type)
		throws Exception {
	connection = mock(Connection.class);
	statement = mock(Statement.class);
	resultSet = mock(ResultSet.class);
	resultSetMetaData = mock(ResultSetMetaData.class);

	given(connection.createStatement()).willReturn(statement);
	given(statement.executeQuery(anyString())).willReturn(resultSet);
	given(resultSet.getMetaData()).willReturn(resultSetMetaData);

	given(resultSet.next()).willReturn(true, false);
	given(resultSet.getString(1)).willReturn("Bubba");
	given(resultSet.getLong(2)).willReturn(22L);
	given(resultSet.getTimestamp(3)).willReturn(new Timestamp(1221222L));
	given(resultSet.getBigDecimal(4)).willReturn(new BigDecimal("1234.56"));
	given(resultSet.wasNull()).willReturn(type == MockType.TWO ? true : false);

	given(resultSetMetaData.getColumnCount()).willReturn(4);
	given(resultSetMetaData.getColumnLabel(1)).willReturn(
			type == MockType.THREE ? "Last Name" : "name");
	given(resultSetMetaData.getColumnLabel(2)).willReturn("age");
	given(resultSetMetaData.getColumnLabel(3)).willReturn("birth_date");
	given(resultSetMetaData.getColumnLabel(4)).willReturn("balance");

	jdbcTemplate = new JdbcTemplate();
	jdbcTemplate.setDataSource(new SingleConnectionDataSource(connection, false));
	jdbcTemplate.setExceptionTranslator(new SQLStateSQLExceptionTranslator());
	jdbcTemplate.afterPropertiesSet();
}
 
Example #10
Source File: StoredProcedureTests.java    From spring4-understanding with Apache License 2.0 5 votes vote down vote up
/**
 * Confirm no connection was used to get metadata. Does not use superclass replay
 * mechanism.
 *
 * @throws Exception
 */
@Test
public void testStoredProcedureConfiguredViaJdbcTemplateWithCustomExceptionTranslator()
		throws Exception {
	given(callableStatement.execute()).willReturn(false);
	given(callableStatement.getUpdateCount()).willReturn(-1);
	given(callableStatement.getObject(2)).willReturn(5);
	given(connection.prepareCall("{call " + StoredProcedureConfiguredViaJdbcTemplate.SQL + "(?, ?)}")
			).willReturn(callableStatement);

	class TestJdbcTemplate extends JdbcTemplate {

		int calls;

		@Override
		public Map<String, Object> call(CallableStatementCreator csc,
				List<SqlParameter> declaredParameters) throws DataAccessException {
			calls++;
			return super.call(csc, declaredParameters);
		}
	}
	TestJdbcTemplate t = new TestJdbcTemplate();
	t.setDataSource(dataSource);
	// Will fail without the following, because we're not able to get a connection
	// from the DataSource here if we need to to create an ExceptionTranslator
	t.setExceptionTranslator(new SQLStateSQLExceptionTranslator());
	StoredProcedureConfiguredViaJdbcTemplate sp = new StoredProcedureConfiguredViaJdbcTemplate(t);

	assertEquals(sp.execute(11), 5);
	assertEquals(1, t.calls);

	verify(callableStatement).setObject(1, 11, Types.INTEGER);
	verify(callableStatement).registerOutParameter(2, Types.INTEGER);
}
 
Example #11
Source File: RowMapperTests.java    From java-technology-stack with MIT License 5 votes vote down vote up
@Before
public void setUp() throws SQLException {
	given(connection.createStatement()).willReturn(statement);
	given(connection.prepareStatement(anyString())).willReturn(preparedStatement);
	given(statement.executeQuery(anyString())).willReturn(resultSet);
	given(preparedStatement.executeQuery()).willReturn(resultSet);
	given(resultSet.next()).willReturn(true, true, false);
	given(resultSet.getString(1)).willReturn("tb1", "tb2");
	given(resultSet.getInt(2)).willReturn(1, 2);

	template.setDataSource(new SingleConnectionDataSource(connection, false));
	template.setExceptionTranslator(new SQLStateSQLExceptionTranslator());
	template.afterPropertiesSet();
}
 
Example #12
Source File: JdbcTemplateTests.java    From java-technology-stack with MIT License 5 votes vote down vote up
/**
 * Test that we see an SQLException translated using Error Code.
 * If we provide the SQLExceptionTranslator, we shouldn't use a connection
 * to get the metadata
 */
@Test
public void testUseCustomSQLErrorCodeTranslator() throws Exception {
	// Bad SQL state
	final SQLException sqlException = new SQLException("I have a known problem", "07000", 1054);
	final String sql = "SELECT ID FROM CUSTOMER";

	given(this.resultSet.next()).willReturn(true);
	given(this.connection.createStatement()).willReturn(this.preparedStatement);

	JdbcTemplate template = new JdbcTemplate();
	template.setDataSource(this.dataSource);
	// Set custom exception translator
	template.setExceptionTranslator(new SQLStateSQLExceptionTranslator());
	template.afterPropertiesSet();

	this.thrown.expect(BadSqlGrammarException.class);
	this.thrown.expect(exceptionCause(sameInstance(sqlException)));
	try {
		template.query(sql, (RowCallbackHandler) rs -> {
			throw sqlException;
		});
	}
	finally {
		verify(this.resultSet).close();
		verify(this.preparedStatement).close();
		verify(this.connection).close();
	}
}
 
Example #13
Source File: AbstractRowMapperTests.java    From java-technology-stack with MIT License 5 votes vote down vote up
@SuppressWarnings("unchecked")
public Mock(MockType type) throws Exception {
	connection = mock(Connection.class);
	statement = mock(Statement.class);
	resultSet = mock(ResultSet.class);
	resultSetMetaData = mock(ResultSetMetaData.class);

	given(connection.createStatement()).willReturn(statement);
	given(statement.executeQuery(anyString())).willReturn(resultSet);
	given(resultSet.getMetaData()).willReturn(resultSetMetaData);

	given(resultSet.next()).willReturn(true, false);
	given(resultSet.getString(1)).willReturn("Bubba");
	given(resultSet.getLong(2)).willReturn(22L);
	given(resultSet.getTimestamp(3)).willReturn(new Timestamp(1221222L));
	given(resultSet.getObject(anyInt(), any(Class.class))).willThrow(new SQLFeatureNotSupportedException());
	given(resultSet.getDate(3)).willReturn(new java.sql.Date(1221222L));
	given(resultSet.getBigDecimal(4)).willReturn(new BigDecimal("1234.56"));
	given(resultSet.wasNull()).willReturn(type == MockType.TWO);

	given(resultSetMetaData.getColumnCount()).willReturn(4);
	given(resultSetMetaData.getColumnLabel(1)).willReturn(
			type == MockType.THREE ? "Last Name" : "name");
	given(resultSetMetaData.getColumnLabel(2)).willReturn("age");
	given(resultSetMetaData.getColumnLabel(3)).willReturn("birth_date");
	given(resultSetMetaData.getColumnLabel(4)).willReturn("balance");

	jdbcTemplate = new JdbcTemplate();
	jdbcTemplate.setDataSource(new SingleConnectionDataSource(connection, false));
	jdbcTemplate.setExceptionTranslator(new SQLStateSQLExceptionTranslator());
	jdbcTemplate.afterPropertiesSet();
}
 
Example #14
Source File: StoredProcedureTests.java    From java-technology-stack with MIT License 5 votes vote down vote up
/**
 * Confirm no connection was used to get metadata. Does not use superclass replay
 * mechanism.
 *
 * @throws Exception
 */
@Test
public void testStoredProcedureConfiguredViaJdbcTemplateWithCustomExceptionTranslator()
		throws Exception {
	given(callableStatement.execute()).willReturn(false);
	given(callableStatement.getUpdateCount()).willReturn(-1);
	given(callableStatement.getObject(2)).willReturn(5);
	given(connection.prepareCall("{call " + StoredProcedureConfiguredViaJdbcTemplate.SQL + "(?, ?)}")
			).willReturn(callableStatement);

	class TestJdbcTemplate extends JdbcTemplate {

		int calls;

		@Override
		public Map<String, Object> call(CallableStatementCreator csc,
				List<SqlParameter> declaredParameters) throws DataAccessException {
			calls++;
			return super.call(csc, declaredParameters);
		}
	}
	TestJdbcTemplate t = new TestJdbcTemplate();
	t.setDataSource(dataSource);
	// Will fail without the following, because we're not able to get a connection
	// from the DataSource here if we need to create an ExceptionTranslator
	t.setExceptionTranslator(new SQLStateSQLExceptionTranslator());
	StoredProcedureConfiguredViaJdbcTemplate sp = new StoredProcedureConfiguredViaJdbcTemplate(t);

	assertEquals(5, sp.execute(11));
	assertEquals(1, t.calls);

	verify(callableStatement).setObject(1, 11, Types.INTEGER);
	verify(callableStatement).registerOutParameter(2, Types.INTEGER);
}
 
Example #15
Source File: JooqExceptionTranslator.java    From micronaut-sql with Apache License 2.0 5 votes vote down vote up
private SQLExceptionTranslator getTranslator(ExecuteContext context) {
    SQLDialect dialect = context.configuration().dialect();
    if (dialect != null && dialect.thirdParty() != null) {
        String dbName = dialect.thirdParty().springDbName();
        if (dbName != null) {
            return new SQLErrorCodeSQLExceptionTranslator(dbName);
        }
    }
    return new SQLStateSQLExceptionTranslator();
}
 
Example #16
Source File: RowMapperTests.java    From spring-analysis-note with MIT License 5 votes vote down vote up
@Before
public void setUp() throws SQLException {
	given(connection.createStatement()).willReturn(statement);
	given(connection.prepareStatement(anyString())).willReturn(preparedStatement);
	given(statement.executeQuery(anyString())).willReturn(resultSet);
	given(preparedStatement.executeQuery()).willReturn(resultSet);
	given(resultSet.next()).willReturn(true, true, false);
	given(resultSet.getString(1)).willReturn("tb1", "tb2");
	given(resultSet.getInt(2)).willReturn(1, 2);

	template.setDataSource(new SingleConnectionDataSource(connection, false));
	template.setExceptionTranslator(new SQLStateSQLExceptionTranslator());
	template.afterPropertiesSet();
}
 
Example #17
Source File: StoredProcedureTests.java    From spring-analysis-note with MIT License 5 votes vote down vote up
/**
 * Confirm no connection was used to get metadata. Does not use superclass replay
 * mechanism.
 */
@Test
public void testStoredProcedureConfiguredViaJdbcTemplateWithCustomExceptionTranslator()
		throws Exception {
	given(callableStatement.execute()).willReturn(false);
	given(callableStatement.getUpdateCount()).willReturn(-1);
	given(callableStatement.getObject(2)).willReturn(5);
	given(connection.prepareCall("{call " + StoredProcedureConfiguredViaJdbcTemplate.SQL + "(?, ?)}")
			).willReturn(callableStatement);

	class TestJdbcTemplate extends JdbcTemplate {

		int calls;

		@Override
		public Map<String, Object> call(CallableStatementCreator csc,
				List<SqlParameter> declaredParameters) throws DataAccessException {
			calls++;
			return super.call(csc, declaredParameters);
		}
	}
	TestJdbcTemplate t = new TestJdbcTemplate();
	t.setDataSource(dataSource);
	// Will fail without the following, because we're not able to get a connection
	// from the DataSource here if we need to create an ExceptionTranslator
	t.setExceptionTranslator(new SQLStateSQLExceptionTranslator());
	StoredProcedureConfiguredViaJdbcTemplate sp = new StoredProcedureConfiguredViaJdbcTemplate(t);

	assertEquals(5, sp.execute(11));
	assertEquals(1, t.calls);

	verify(callableStatement).setObject(1, 11, Types.INTEGER);
	verify(callableStatement).registerOutParameter(2, Types.INTEGER);
}
 
Example #18
Source File: HibernateTransactionManagerTests.java    From spring4-understanding with Apache License 2.0 4 votes vote down vote up
@Test
public void testTransactionCommit() throws Exception {
	final DataSource ds = mock(DataSource.class);
	Connection con = mock(Connection.class);
	final SessionFactory sf = mock(SessionFactory.class);
	final Session session = mock(Session.class);
	Transaction tx = mock(Transaction.class);
	Query query = mock(Query.class);

	final List list = new ArrayList();
	list.add("test");
	given(con.getTransactionIsolation()).willReturn(Connection.TRANSACTION_READ_COMMITTED);
	given(sf.openSession()).willReturn(session);
	given(session.getTransaction()).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);

	LocalSessionFactoryBean lsfb = new LocalSessionFactoryBean() {
		@Override
		protected SessionFactory newSessionFactory(Configuration config) throws HibernateException {
			return sf;
		}
	};
	lsfb.afterPropertiesSet();
	final SessionFactory sfProxy = lsfb.getObject();

	HibernateTransactionManager tm = new HibernateTransactionManager();
	tm.setJdbcExceptionTranslator(new SQLStateSQLExceptionTranslator());
	tm.setSessionFactory(sfProxy);
	tm.setDataSource(ds);
	TransactionTemplate tt = new TransactionTemplate(tm);
	tt.setIsolationLevel(TransactionDefinition.ISOLATION_SERIALIZABLE);
	tt.setTimeout(10);
	assertTrue("Hasn't thread session", !TransactionSynchronizationManager.hasResource(sfProxy));
	assertTrue("Hasn't thread connection", !TransactionSynchronizationManager.hasResource(ds));
	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(sfProxy));
			assertTrue("Has thread connection", TransactionSynchronizationManager.hasResource(ds));
			assertFalse(TransactionSynchronizationManager.isCurrentTransactionReadOnly());
			assertTrue(TransactionSynchronizationManager.isActualTransactionActive());
			HibernateTemplate ht = new HibernateTemplate(sfProxy);
			return ht.find("some query string");
		}
	});
	assertTrue("Correct result list", result == list);

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

	verify(con).setTransactionIsolation(Connection.TRANSACTION_SERIALIZABLE);
	verify(con).setTransactionIsolation(Connection.TRANSACTION_READ_COMMITTED);
	verify(tx).setTimeout(10);
	verify(tx).begin();
	verify(tx).commit();
	verify(session).close();
}
 
Example #19
Source File: HibernateTransactionManagerTests.java    From spring4-understanding with Apache License 2.0 4 votes vote down vote up
@Test
public void testTransactionCommitWithEarlyFlush() throws Exception {
	final DataSource ds = mock(DataSource.class);
	Connection con = mock(Connection.class);
	final SessionFactory sf = mock(SessionFactory.class);
	final Session session = mock(Session.class);
	Transaction tx = mock(Transaction.class);
	Query query = mock(Query.class);

	final List list = new ArrayList();
	list.add("test");
	given(con.getTransactionIsolation()).willReturn(Connection.TRANSACTION_READ_COMMITTED);
	given(sf.openSession()).willReturn(session);
	given(session.getTransaction()).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.getFlushMode()).willReturn(FlushMode.AUTO);
	given(session.isConnected()).willReturn(true);

	LocalSessionFactoryBean lsfb = new LocalSessionFactoryBean() {
		@Override
		protected SessionFactory newSessionFactory(Configuration config) throws HibernateException {
			return sf;
		}
	};
	lsfb.afterPropertiesSet();
	final SessionFactory sfProxy = lsfb.getObject();

	HibernateTransactionManager tm = new HibernateTransactionManager();
	tm.setJdbcExceptionTranslator(new SQLStateSQLExceptionTranslator());
	tm.setSessionFactory(sfProxy);
	tm.setDataSource(ds);
	tm.setEarlyFlushBeforeCommit(true);
	TransactionTemplate tt = new TransactionTemplate(tm);
	tt.setIsolationLevel(TransactionDefinition.ISOLATION_SERIALIZABLE);
	tt.setTimeout(10);
	assertTrue("Hasn't thread session", !TransactionSynchronizationManager.hasResource(sfProxy));
	assertTrue("Hasn't thread connection", !TransactionSynchronizationManager.hasResource(ds));
	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(sfProxy));
			assertTrue("Has thread connection", TransactionSynchronizationManager.hasResource(ds));
			assertFalse(TransactionSynchronizationManager.isCurrentTransactionReadOnly());
			assertTrue(TransactionSynchronizationManager.isActualTransactionActive());
			HibernateTemplate ht = new HibernateTemplate(sfProxy);
			return ht.find("some query string");
		}
	});
	assertTrue("Correct result list", result == list);

	assertTrue("Hasn't thread session", !TransactionSynchronizationManager.hasResource(sfProxy));
	assertTrue("Hasn't thread connection", !TransactionSynchronizationManager.hasResource(ds));
	assertTrue("JTA synchronizations not active", !TransactionSynchronizationManager.isSynchronizationActive());
	InOrder ordered = inOrder(con);
	ordered.verify(con).setTransactionIsolation(Connection.TRANSACTION_SERIALIZABLE);
	ordered.verify(con).setTransactionIsolation(Connection.TRANSACTION_READ_COMMITTED);
	verify(tx).setTimeout(10);
	verify(tx).begin();
	verify(session).flush();
	verify(session).setFlushMode(FlushMode.MANUAL);
	verify(tx).commit();
	verify(session).close();
}
 
Example #20
Source File: SessionFactoryUtils.java    From lams with GNU General Public License v2.0 3 votes vote down vote up
/**
 * Create an appropriate SQLExceptionTranslator for the given SessionFactory.
 * If a DataSource is found, a SQLErrorCodeSQLExceptionTranslator for the DataSource
 * is created; else, a SQLStateSQLExceptionTranslator as fallback.
 * @param sessionFactory the SessionFactory to create the translator for
 * @return the SQLExceptionTranslator
 * @see #getDataSource
 * @see org.springframework.jdbc.support.SQLErrorCodeSQLExceptionTranslator
 * @see org.springframework.jdbc.support.SQLStateSQLExceptionTranslator
 */
public static SQLExceptionTranslator newJdbcExceptionTranslator(SessionFactory sessionFactory) {
	DataSource ds = getDataSource(sessionFactory);
	if (ds != null) {
		return new SQLErrorCodeSQLExceptionTranslator(ds);
	}
	return new SQLStateSQLExceptionTranslator();
}
 
Example #21
Source File: PersistenceManagerFactoryUtils.java    From spring4-understanding with Apache License 2.0 3 votes vote down vote up
/**
 * Create an appropriate SQLExceptionTranslator for the given PersistenceManagerFactory.
 * <p>If a DataSource is found, creates a SQLErrorCodeSQLExceptionTranslator for the
 * DataSource; else, falls back to a SQLStateSQLExceptionTranslator.
 * @param connectionFactory the connection factory of the PersistenceManagerFactory
 * (may be {@code null})
 * @return the SQLExceptionTranslator (never {@code null})
 * @see javax.jdo.PersistenceManagerFactory#getConnectionFactory()
 * @see org.springframework.jdbc.support.SQLErrorCodeSQLExceptionTranslator
 * @see org.springframework.jdbc.support.SQLStateSQLExceptionTranslator
 */
static SQLExceptionTranslator newJdbcExceptionTranslator(Object connectionFactory) {
	// Check for PersistenceManagerFactory's DataSource.
	if (connectionFactory instanceof DataSource) {
		return new SQLErrorCodeSQLExceptionTranslator((DataSource) connectionFactory);
	}
	else {
		return new SQLStateSQLExceptionTranslator();
	}
}
 
Example #22
Source File: SessionFactoryUtils.java    From spring4-understanding with Apache License 2.0 3 votes vote down vote up
/**
 * Create an appropriate SQLExceptionTranslator for the given SessionFactory.
 * If a DataSource is found, a SQLErrorCodeSQLExceptionTranslator for the DataSource
 * is created; else, a SQLStateSQLExceptionTranslator as fallback.
 * @param sessionFactory the SessionFactory to create the translator for
 * @return the SQLExceptionTranslator
 * @see #getDataSource
 * @see org.springframework.jdbc.support.SQLErrorCodeSQLExceptionTranslator
 * @see org.springframework.jdbc.support.SQLStateSQLExceptionTranslator
 */
public static SQLExceptionTranslator newJdbcExceptionTranslator(SessionFactory sessionFactory) {
	DataSource ds = getDataSource(sessionFactory);
	if (ds != null) {
		return new SQLErrorCodeSQLExceptionTranslator(ds);
	}
	return new SQLStateSQLExceptionTranslator();
}
 
Example #23
Source File: PersistenceManagerFactoryUtils.java    From lams with GNU General Public License v2.0 3 votes vote down vote up
/**
 * Create an appropriate SQLExceptionTranslator for the given PersistenceManagerFactory.
 * <p>If a DataSource is found, creates a SQLErrorCodeSQLExceptionTranslator for the
 * DataSource; else, falls back to a SQLStateSQLExceptionTranslator.
 * @param connectionFactory the connection factory of the PersistenceManagerFactory
 * (may be {@code null})
 * @return the SQLExceptionTranslator (never {@code null})
 * @see javax.jdo.PersistenceManagerFactory#getConnectionFactory()
 * @see org.springframework.jdbc.support.SQLErrorCodeSQLExceptionTranslator
 * @see org.springframework.jdbc.support.SQLStateSQLExceptionTranslator
 */
static SQLExceptionTranslator newJdbcExceptionTranslator(Object connectionFactory) {
	// Check for PersistenceManagerFactory's DataSource.
	if (connectionFactory instanceof DataSource) {
		return new SQLErrorCodeSQLExceptionTranslator((DataSource) connectionFactory);
	}
	else {
		return new SQLStateSQLExceptionTranslator();
	}
}