iis服务器助手广告广告
返回顶部
首页 > 资讯 > 数据库 >Mybatis框架详解(全)
  • 891
分享到

Mybatis框架详解(全)

mybatisjavamysql 2023-09-01 09:09:42 891人浏览 薄情痞子
摘要

目录 MyBatis简介 MyBatis整体架构及运行流程 1.数据源配置文件 2.Sql映射文件 3.会话工厂与会话 4.运行流程 mybatis实现增删改查 Mybatis的获取参数的方式 mapper中自定义映射 mybatis注解

目录

MyBatis简介

MyBatis整体架构及运行流程

1.数据源配置文件

2.Sql映射文件

3.会话工厂与会话

4.运行流程

mybatis实现增删改查

Mybatis的获取参数的方式

mapper中自定义映射

mybatis注解开发

mybatis缓存

mybatis分页插件


mybatis简介

MyBatis 是一款优秀的持久层框架,它支持自定义 sql、存储过程以及高级映射。MyBatis 免除了几乎所有的 JDBC 代码以及设置参数和获取结果集的工作。MyBatis 可以通过简单的 XML 或注解来配置和映射原始类型、接口和 Java POJO(Plain Old Java Objects,普通老式 Java 对象)为数据库中的记录

2010年这个项目由apache software foundation 迁移到了Google code,并且改名为MyBatis 。2013年11月迁移到GitHub

回顾JDBC的使用步骤:

  • 加载驱动

Class.forName("com.Mysql.jdbc.Driver");
  • 获取连接对象

DiverManerger.getConnection(url,username,passWord)
  • 获取执行sql的Statement对象

connection.CreateStatement();
  • 执行sql语句

  • 处理结果集

  • 释放连接

connection.Close()

与JDBC相比:

  1. Mybatis通过参数映射方式,可以将参数灵活的配置在SQL语句中的配置文件中,避免在Java类中配置参数

  2. Mybatis通过输出映射机制,将结果集的检索自动映射成相应的Java对象,避免对结果集手工检索

  3. Mybatis可以通过Xml配置文件对数据库连接进行管理

MyBatis整体架构及运行流程

Mybatis整体构造由 数据源配置文件、Sql映射文件、会话工厂、会话、执行器和底层封装对象组成

1.数据源配置文件

通过配置的方式将数据库的配置信息从应用程序中独立出来,由独立的模块管理和配置。Mybatis的数据源配置文件包含数据库驱动、数据库连接地址、用户名密码、事务管理等,还可以配置连接池的连接数、空闲时间等

一个MapConfig.xml基本的配置信息如下:

                                                                            

mybatis mapper文件映射

 

 设置资源文件路径

Maven中默认是只会打包resource下的资源文件。如果我们的文件不放在resource, 则需要通过配置告知Maven

2.Sql映射文件

Mybatis中所有数据库的操作都会基于该映射文件和配置的sql语句,在这个配置文件中可以配置任何类型的sql语句。框架会根据配置文件中的参数配置,完成对sql语句以及输入输出参数的映射配置。

Mapper.xml配置文件大致如下:

-- sql语句

 

3.会话工厂与会话

Mybatis中会话工厂SqlSessionFactory类可以通过加载资源文件,读取数据源配置MapConfig.xml信息,从而产生一种可以与数据库交互的会话实例SqlSession,会话实例SqlSession根据Mapper.xml文件中配置的sql,对数据库进行操作。

4.运行流程

会话工厂SqlSessionFactory通过加载资源文件获取MapConfig.xml配置文件信息,然后生成可以与数据库交互的会话实例SqlSession。会话实例可以根据Mapper配置文件中的Sql配置去执行相应的增删改查操作

执行流程图:

mybatis实现增删改查

public class TestStudent {    @Test    public void test01(){        try {//加载配置文件            InputStream in = Resources.getResourceAsStream("config/mybatis-config.xml");            //获取sqlSession对象            SqlSession sqlSession = new SqlSessionFactoryBuilder().build(in).openSession();            //查询所有学生信息        List students = sqlSession.selectList("cn.kgc.mybatis.dao.StudentDao.getAll");            students.forEach(student -> System.out.println(student) );        } catch (IOException e) {            e.printStackTrace();        }    }    @Test    public void test02(){//查询一个学生信息        try {//加载配置文件            InputStream in = Resources.getResourceAsStream("config/mybatis-config.xml");            //获取sqlSession对象            SqlSession sqlSession = new SqlSessionFactoryBuilder().build(in).openSession();            //根据用户名查询一个学生信息            Student student = sqlSession.selectOne("cn.kGC.mybatis.dao.StudentDao.findOne","tom");            System.out.println(student);            sqlSession.close();        } catch (IOException e) {            e.printStackTrace();        }    }    @Test    public void test03() {//添加一个学生信息        try {//加载配置文件            InputStream in = Resources.getResourceAsStream("config/mybatis-config.xml");            //获取sqlSession对象            SqlSession sqlSession = new SqlSessionFactoryBuilder().build(in).openSession();            //添加一个学生信息            Student student = Student.builder().stuBirth(new Date()).stuName("lilei").stuNo("2021073001").stuSex("男").build();            int i = sqlSession.insert("cn.kgc.mybatis.dao.StudentDao.addOne", student);            System.out.println(i);            sqlSession.commit();            sqlSession.close();        } catch (IOException e) {            e.printStackTrace();        }    }    @Test    public void test04() {//删除一个学生信息        try{            InputStream in = Resources.getResourceAsStream("config/mybatis-config.xml");            //获取sqlSession对象 同时可设置事务的自动提交  openSession(true)            SqlSession sqlSession = new SqlSessionFactoryBuilder().build(in).openSession();            int delete = sqlSession.delete("cn.kgc.mybatis.dao.StudentDao.delOne","lilei" );            sqlSession.commit();            sqlSession.close();            System.out.println(delete);        }catch (Exception e){            e.printStackTrace();        }    }    @Test    public void test05() {//修改一个学生信息        try{            InputStream in = Resources.getResourceAsStream("config/mybatis-config.xml");            //获取sqlSession对象            SqlSession sqlSession = new SqlSessionFactoryBuilder().build(in).openSession();            Student student = Student.builder().stuBirth(new Date()).stuName("lili").stuNo("2021073001").stuSex("女").build();            int delete = sqlSession.update("cn.kgc.mybatis.dao.StudentDao.updateStudent",student);            sqlSession.commit();            sqlSession.close();            System.out.println(delete);        }catch (Exception e){            e.printStackTrace();        }    }}

 

mybatis中使用log4j日志工具

配置mybatis-config.xml

开启驼峰命名  

设置别名

 

配置log4j.properties文件,放置在resources目录下

log4j.rootLogger=DEBUG,Console#Consolelog4j.appender.Console=org.apache.log4j.ConsoleAppenderlog4j.appender.console.Target=System.outlog4j.appender.Console.layout=org.apache.log4j.PatternLayoutlog4j.appender.Console.layout.ConversionPattern=%d [%t] %-5p [%c] - %m%nlog4j.logger.org.apache=ERRORlog4j.logger.org.mybatis=ERRORlog4j.logger.org.springframework=ERROR#这个需要log4j.logger.log4jdbc.debug=ERRORlog4j.logger.com.gk.mapper=ERRORlog4j.logger.jdbc.audit=ERRORlog4j.logger.jdbc.resultset=ERROR#这个打印SQL语句非常重要log4j.logger.jdbc.sqlonly=DEBUGlog4j.logger.jdbc.sqltiming=ERRORlog4j.logger.jdbc.connection=FATAL

 

 使用mapper代理对象实现增删改查

public class TestStudentMapper {    SqlSessionFactory factory;    @Before    public void init(){        try {            InputStream  in = Resources.getResourceAsStream("config/mybatis-config.xml");            SqlSessionFactoryBuilder sfb = new SqlSessionFactoryBuilder();            factory = sfb.build(in);        } catch (IOException e) {            e.printStackTrace();        }    }    @Test    public void test01(){            //开启事务自动提交            SqlSession sqlSession = factory.openSession(true);            //获取dao层的代理对象            StudentDao studentDao = sqlSession.getMapper(StudentDao.class);            List students = studentDao.getAll();            students.forEach(student -> System.out.println(student));    }    @Test    public void test02(){ //添加数据        SqlSession sqlSession = factory.openSession(true);        Student student = Student.builder().stuSex("男").stuNo("2021073100").stuName("李四").stuBirth(new Date()).build();        StudentDao studentDao = sqlSession.getMapper(StudentDao.class);        Integer line = studentDao.addOne(student);        System.out.println(line);    }    @Test    public  void test03(){//删除一条数据        SqlSession sqlSession = factory.openSession(true);        StudentDao studentDao = sqlSession.getMapper(StudentDao.class);        Integer line = studentDao.delOne("李四");        System.out.println(line);    }    @Test    public void test04() { //修改数据        SqlSession sqlSession = factory.openSession(true);        StudentDao studentDao = sqlSession.getMapper(StudentDao.class);        Student student = Student.builder().stuSex("女").stuNo("2021073100").stuName("李四").stuBirth(new Date()).build();        Integer line = studentDao.updateOne(student);        System.out.println(line);    }        @Test    public void test06(){//模糊查询一个学生信息 一个参数        SqlSession sqlSession = factory.openSession(true);        StudentDao studentDao = sqlSession.getMapper(StudentDao.class);        List students = studentDao.selectLikeName("li");        System.out.println(students.toString());    }    @Test    public void test07(){//模糊查询一个学生信息 两个参数        SqlSession sqlSession = factory.openSession(true);        StudentDao studentDao = sqlSession.getMapper(StudentDao.class);        List students = studentDao.selectLikeName2("li", "2021072902");        System.out.println(students.toString());    }     @Test    public void test08(){//模糊查询一个学生信息 一个集合参数  mapper文件中按照key取值        SqlSession sqlSession = factory.openSession(true);        StudentDao studentDao = sqlSession.getMapper(StudentDao.class);        HashMap map = new HashMap<>();        map.put("stuname","li");        map.put("stuno", "2021072902");        List students = studentDao.selectLikeName3(map);        System.out.println(students.toString());    }}

 

Mybatis的获取参数的方式

方式1:${} 字符串拼接

方式2:#{} 占位符

1.Mapper接口参数为单个参数

2.Mapper接口参数是多个参数的获取

mybatis在处理多个参数时,会将多个参数保存到map集合中会 以 agr0 ,agr1或param1 param2为键 以参数位置进行存储

 

3.将参数设为map集合进行数据的传递

 

4.通过注解@param("键名")设置参数的获取名字

 

5.将多个参数设置成对象进行数据的传递

 

Mybatis中的模糊查询

 6.批量删除

mapper中自定义映射

自定义映射的用法之一,解决表格查询的字段名和实体类中不一致的情况

 

mybatis对象的关联关系

一对多关系处理(一方)

                                                                                                                                                             注:延迟加载设置  :1.  2.   3.4.1之前的版本需要设置                select  * from emp  where eid = #{eid}    

 

 一对多关系处理(多方)

                                                                                                                                                                 select emp.* ,dept.* from dept left join emp on dept.id = emp.deptno where id = #{id}