使用jdbcTemplate查询不到刚刚插入的记录?

如题,本人使用Spring提供的AbstractTransactionalDataSourceSpringContextTests对服务层进行集成测试

测试的目的是向数据库插入一条记录,然后立即检索出来。下面是我的测试代码:


public void testSaveUser() {
User newUser = createUser();
try {
userService.saveUser(newUser);
assertTrue(true);
//setComplete();
String sql =
"Select USERNAME from NEWSLETTER_USER where UPPER(USERNAME)= ?";
String userName = (String) jdbcTemplate.queryForObject(sql,
new Object[] {
"PAUL" }, java.lang.String.class);
assertNotNull(userName);
assertEquals(userName, newUser.getUserName());
} catch (NewsletterException ne) {
fail(ne.getMessage());
}
}

请注意该方法里面的setComplete()方法,一开始我并没有提交事务,于是出现了saveUser执行成功,但jdbcTemplate.queryForObject执行时查询不到记录,导致assertNotNull(userName)处失败。

后来我把setComplete()处的注释去掉,再次测试。发现数据库中已经有了一条记录,将SQL语句拷贝到数据库中执行可以返回正确的结果,但使用jdbcTemplate查询依然失败,同样提示查询不到记录。

请问这是为什么?为什么在提交后还查不到数据?

事务没有完成,关闭事务取决你使用什么事务如jdbc/jTA

我采用的是jdbc的事务,Spring中配置如下:


<!-- User Service Definition -->
<bean id="userServiceTarget"
class=
"com.newsletter.service.impl.UserServiceImpl">
<property name=
"userDao">
<ref local=
"userDao" />
</property>
<property name=
"systemMessage">
<ref local=
"systemMessage" />
</property>
</bean>

<!-- Transactional proxy for the User Service -->
<bean id=
"userService"
class=
"org.springframework.transaction.interceptor.TransactionProxyFactoryBean">
<property name=
"transactionManager">
<ref local=
"transactionManager" />
</property>
<property name=
"target">
<ref local=
"userServiceTarget" />
</property>
<property name=
"transactionAttributes">
<props>
<prop key=
"get*">PROPAGATION_REQUIRED,readOnly</prop>
<prop key=
"save*">PROPAGATION_REQUIRED</prop>
<prop key=
"update*">PROPAGATION_REQUIRED</prop>
<prop key=
"delete*">PROPAGATION_REQUIRED</prop>
</props>
</property>
</bean>

另你提到事务没有完成,为什么这样说呢?难道不是在我调用setComplete()时事务就已经提交了吗?请指教