ssm-spring集成mybatis事务
事务
MyBatis-Spring库的引入,无需创建新的MyBatis事务管理器,就能使MyBatis接入到Spring事。 引入的方式既可以是注解,也可以是aop。
未配置事务实例
首先来看看未配置事务时,执行一组先增加后删除(删除异常)的数据库语句场景。数据库连接配置延用之前的,这里不再介绍。
- 编写DAO
public interface StudentMapper {
void add(Map<Object, Object> student);
void delete(String name);
}
声明了新增和删除两个接口。
- mapper配置文件中编写对应sql:
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.zx.demo.mybatis.spring.mapper.StudentMapper">
<insert id="add">
INSERT INTO student (`name`,sex) VALUES (#{name},#{sex});
</insert>
<delete id="delete">
DELETE FROM student WHERE `name` = #{name};
</delete>
</mapper>
- 分别编写测试方法测试正确的增加和删除:
- 增加:
@Test
public void testTransaction() throws Exception {
ApplicationContext context = new ClassPathXmlApplicationContext("spring-context.xml");
StudentMapper mapper = (StudentMapper) context.getBean("exampleMapper");
Map<Object, Object> student = new HashMap<>();
student.put("name", "曹操");
student.put("sex", "男");
mapper.add(student);
}
运行后确定数据库中有写入一条新的数据:
删除: @Test
public void testTransaction() throws Exception {
ApplicationContext context = new ClassPathXmlApplicationContext("spring-context.xml");
StudentMapper mapper = (StudentMapper) context.getB