栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

Spring整合Mybatis和声明式事务

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

Spring整合Mybatis和声明式事务

文章目录

步骤代码示例声明式事务

步骤
    导入相关jar包

junitmybatismysql驱动spring相关aop织入mybatis-spring

    编写配置文件测试
代码示例
    准备一个可运行发Mybatis项目编写spring-dao.xml文件



    
    
        
        
        
        
    

    
    
        
        
        
        
    

    
    
        
        
    


    编写实现类
package com.bkms.mapper;

import com.bkms.pojo.User;
import org.mybatis.spring.SqlSessionTemplate;

import java.util.List;

public class UserServiceImpl implements UserMapper{
    private SqlSessionTemplate sqlSession;

    public void setSqlSession(SqlSessionTemplate sqlSession) {
        this.sqlSession = sqlSession;
    }

    public List queryAllUser() {
        UserMapper mapper = sqlSession.getMapper(UserMapper.class);
        return mapper.queryAllUser();
    }
}
    编写applicationContext.xml文件



    

    
    
        
    


    测试
import com.bkms.mapper.UserMapper;
import com.bkms.pojo.User;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import java.io.IOException;
import java.util.List;

public class MyTest {
    @Test
    public void testQueryAllUser () throws IOException {
        ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
        UserMapper userMapper = context.getBean("userMapper", UserMapper.class);
        List users = userMapper.queryAllUser();
        for (User user : users) {
            System.out.println(user);
        }
    }
}
声明式事务
    一组业务要么成功,要么失败事务在项目开发中十分重要,涉及到数据一致性问题,不能马虎确保完整性和一致性事务的ACID原则
    原子性,一致性,
    隔离性:多个业务操作同一资源,保证业务不被损坏
    持久性:事务一旦被提交,无论系统发生什么,都不会影响结果

首先要明确2个概念
数据库向用户提供保存当前程序状态的方法,叫事务提交(commit);当事务执行过程中,使数据库忽略当前的状态并回到前面保存的状态的方法叫事务回滚(rollback)

导入并配置声明式事务




    
    
        
        
        
        
    

    
    
        
        
        
        
    

    
    
        
        
    

    
    
        
     

    
    
        
        
            
            
            
            
        
    

    
    
        
        
    


编写Mapper.xml