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

Spring 集成 MyBatis

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

Spring 集成 MyBatis

  • Spring和MyBatis整合时,MyBatis的事务是自动提交的
项目架构

第一步 创建做为数据载体的domain

public class Student {
    public String id;
    public String name;
    public int age;
    public String sex;

    public Student() {
    }

    public Student(String id, String name, int age, String sex) {
        this.id = id;
        this.name = name;
        this.age = age;
        this.sex = sex;
    }

    public void setId(String id) {
        this.id = id;
    }

    public void setName(String name) {
        this.name = name;
    }

    public void setAge(int age) {
        this.age = age;
    }

    public void setSex(String sex) {
        this.sex = sex;
    }
}

第二步 创建与数据交互的dao对象

public interface StudentDao {
    List selectAll();
}

创建对象的同时完成 dao.xml 文件





    


第三步 创建service接口和对象
service接口

public interface StudentService {
    void selectAll();
}

接口实现类

public class StudentServiceImpl implements StudentService {
    private StudentDao studentDao;

    public void setStudentDao(StudentDao studentDao){
        this.studentDao = studentDao;
    }

    public void selectAll(){
        System.out.println("Executing selectAll-----------------------");
        List students = studentDao.selectAll();
        for(Student stu:students){
            System.out.println(stu.name);
        }
    }
}

第四步 创建MyBatis主配置文件





    
        
    

    
        
    

    
        
    

第五步 创建spring的配置文件:声明mybatis的对象交给spring创建

  1. 数据源Datasource
  2. SqlSessionFactory
  3. Dao对象
  4. 声明自定义的service



    
    

    
    
        
        
        
        
        
    

    
    
        
        
        
    

    
    
        
        
        
        
    
    
    
    
        
    
第六步 创建测试类
public class myTest {
    @Test
    public void test01(){
        ApplicationContext ac = new ClassPathXmlApplicationContext("applicationContext.xml");
        StudentService service = (StudentService) ac.getBean("myStudentService");
        service.selectAll();
    }
}

总结:项目流程就是创建好Spring 容器,Dao对象等,然后通过获取代表Spring容器的ApplicationContext对象,通过该对象获取service对象通过service.selectAll() 进行业务的进行,而在service中会获取与数据库交互的StudentDao,然后对数据库的数据进行查询,并返回。

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/683741.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号