package com.how2java.test;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import com.how2java.service.CategoryService;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("classpath:applicationContext.xml")
public class MybatisTest {
@Autowired
private CategoryService categoryService;
@Test
public void testAddTwo() {
categoryService.deleteAll();
categoryService.addTwo();
}
}
步骤 9 : 进行事务配置
修改applicationContext.xml,添加事务管理器和事务注解扫描器
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:tx="http://www.springframework.org/schema/tx"xmlns:jdbc="http://www.springframework.org/schema/jdbc"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xsi:schemaLocation="
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/jdbc http://www.springframework.org/schema/jdbc/spring-jdbc-3.0.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.0.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.0.xsd
http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd">
com.mysql.jdbc.Driver
jdbc:mysql://localhost:3306/how2java?characterEncoding=UTF-8
root
admin
步骤 10 : 使用注解方式
为addTwo方法加上事务注解
package com.how2java.service.impl;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import com.how2java.mapper.CategoryMapper;
import com.how2java.pojo.Category;
import com.how2java.service.CategoryService;
@Service
public class CategoryServiceImpl implements CategoryService{
@Autowired
CategoryMapper categoryMapper;
public List list(){
return categoryMapper.list();
}
public void deleteAll() {
List cs = list();
for (Category c : cs) {
categoryMapper.delete(c.getId());
}
}
@Override
@Transactional(propagation=Propagation.REQUIRED,rollbackForClassName="Exception")
public void addTwo() {
Category c1 = new Category();
c1.setName("短的名字");
categoryMapper.add(c1);
Category c2 = new Category();
c2.setName("名字长对应字段放不下,名字长对应字段放不下,名字长对应字段放不下,名字长对应字段放不下,名字长对应字段放不下,名字长对应字段放不下,名字长对应字段放不下,名字长对应字段放不下,");
categoryMapper.add(c2);
};
}
步骤 11 : 运行测试类,观察效果
运行测试类MybatisTest发现数据库里是空的。因为第二个数据插入不进去,所以第一个数据的插入也回滚了。