整合ssm的问题(2)
(2)测试spring-springmvc整合时spring的事务管理无法在Controller中起作用的问题
插入数据的时候全是空白:
AccountController类:
@Transactional
@Controller
@RequestMapping("/account")
public class AccountController {
@Autowired
private IAccountService accountService;
/**
* 查询所有数据
*/
@RequestMapping("/test01")
public ModelAndView test01() {
ModelAndView mv = new ModelAndView();
List<Account> allAccount = accountService.findAllAccount();
mv.addObject("accounts", allAccount);
mv.setViewName("success");
return mv;
}
/**
* 插入数据
*/
@RequestMapping("/test04")
public void test04(HttpServletRequest request, HttpServletResponse response, Account account) throws IOException {
accountService.insertAccount(account);
response.sendRedirect(request.getContextPath() + "/account/test01");
}
}
一开始没有添加< input >标签的name属性,导致注入为空
自己找遍了各种配置,没注意这个,找了一天的错误。。。。。
修改之后又发现,执行保存的时候可以保存数据了,但是发生异常数据不能回滚,添加了@Transaction注解,还是不行,最后在springMVC.xml的配置文件中需要加上事务管理
<tx:annotation-driven transaction-manager="transactionManager"/>
即springMVC.xml(上面的约束需要修改,才能支持配置)
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx.xsd">
<!-- 开启注解扫描-->
<context:component-scan base-package="com.ccl.controller">
<context:include-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
</context:component-scan>
<!-- 静态页面可以访问-->
<mvc:default-servlet-handler/>
<!-- 视图解析器对象-->
<bean id="internalResourceViewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/pages/"/>
<property name="suffix" value=".jsp"/>
</bean>
<!-- 开启SpringMVC框架注解的支持-->
<mvc:annotation-driven/>
<!-- 添加对Controller中事务管理-->
<tx:annotation-driven transaction-manager="transactionManager"/>
</beans>
最后测试成功事务能够回滚
(spring中的事务配置必须正确!!!!!!!!!才能用)