Testing jdbctemplate with rollback
I'm having problems testing a transaction flagged readOnly=true. Maybe it's just the way I've implemented it. I have a DAO class with @Transactional(readOnly = true) for all methods. One method is a SAVE, but I forgot to override to readOnly=false. I ran a test against the DAO and the transaction was rolled back, but I thought it should have failed because it was read only. Here's the setup:
PersonDaoImplTest.java
Code:
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = {"classpath*:context.xml" })
@TransactionConfiguration(transactionManager = "transactionManager", defaultRollback = true)
@Transactional
public class PersonDaoImplTest {
@Autowired
PersonDao dao;
@Test
public void testSaveWithReadOnlyTrue() throws Exception {
final Long personId = dao.savePerson(new Person("Steve"));
assertIsNull(personId);
}
}
context.xml
Code:
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.1.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.1.xsd">
<context:component-scan base-package="com.example" />
<context:property-placeholder location="spring.properties" />
<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource"
destroy-method="close">
<property name="driverClassName" value="${jdbc.driver}" />
<property name="url" value="${jdbc.url}" />
<property name="username" value="${jdbc.username}" />
<property name="password" value="${jdbc.password}" />
<property name="defaultAutoCommit" value="false" />
</bean>
<tx:annotation-driven transaction-manager="transactionManager" />
<bean id="transactionManager"
class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource" />
</bean>
</beans>
PersonDaoImpl.java
Code:
@Repository
@Transactional(readOnly = true,propagation = Propagation.REQUIRED)
public class PersonDaoImpl implements PersonDao {
private JdbcTemplate jdbcTemplate;
@Autowired
@Override
public void setDataSource(final DataSource dataSource) {
this.jdbcTemplate = new JdbcTemplate(dataSource);
}
@Override
public Long savePerson(final Person person) {
final SqlUpdate insert = new SqlUpdate(jdbcTemplate.getDataSource(), "insert into person (name) values (?)");
insert.declareParameter(new SqlParameter(Types.VARCHAR));
insert.setGeneratedKeysColumnNames(new String[]{"ID" });
insert.compile();
final GeneratedKeyHolder keyHolder = new GeneratedKeyHolder();
insert.update(
new Object[]{person.getName() }, keyHolder);
return keyHolder.getKey().longValue();
}
}