Spring与Mybatis组合使用事务

1、首先配置Spring与mybatis的spring-config.xml配置文件:
 




    

    
    

    
        
        
        
        

        
        
        
    

    
        
        
        
    

    
        
        
        
    

2、在该配置文件中添加事务配置

    
        
    
    

解释:第一个bean是为了配置事务管理器,第二个tx:annotation是为了开启事务

3、书写一个mapper接口,用来操作数据库\

@Repository
public interface RoleMapper {
//    @Select("select id,role_name as name,note from t_role where id = #{id}")
    public Role getRole(int id);
    @Insert("insert into t_role values(#{role.id},#{role.name},#{role.note})")
    public void insertRole(@Param("role") Role role);
}

4、接下来就是一个Service

@Service
@Transactional
public class RoleService {
    @Autowired
    RoleMapper mapper = null;
    @Autowired
    RoleMapper2 mapper2 = null;

    public void addOneRole(Role role,Role role2){
        mapper.insertRole(role);
//        mapper2.insertRole(role2);
    }

    public void addOneRole2(Role role){
        mapper2.insertRole(role);
    }
}

这里要注意一下:如果将@Transactional配置给Service,那么就说明了此时一个方法中就是一个事务,两个方法会是两个事务,这一点尤为重要,因为如果不注意这一点将会造成transaction的失效,博主已经踩到了大坑,特此注意

5、编写测试:

@Component
public class TestMain {
    public static void main(String[] args) throws ClassNotFoundException, SQLException {
        Logger logger = Logger.getLogger(TestMain.class);
        ApplicationContext context = new ClassPathXmlApplicationContext("spring-config.xml");

        Role role = new Role();
        role.setId(7);
        role.setName("李龙");
        role.setNote("李龙的描述");
        RoleService roleService = (RoleService)context.getBean("roleService");
        roleService.addOneRole(role,null);
        roleService.addOneRole2(null);
    }
}

这里的TestMain你可以看做Controller,博主通过实验证明了,如果调用一个服务的两个方法,那么就是两个事务,如果调用一个方法,那么方法中的程序就会运行在一个事务里!!!!!!!!!!
至此,事务已经使用成功了!!!!!!!!!

你可能感兴趣的:(Spring)