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

Mybatis详解

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

Mybatis详解

目录

1.简介

1.1 什么是Mybatis1.2 为什么需要Mybatis 2、第一个Mybatis程序

2.1 搭建环境2.2 创建一个模块2.3 编写代码2.4测试 3、CRUD

1、namespace2、select3、Insert4、update5、delete6、万能的Map7、模糊查询 4、配置解析

1、核心配置文件2、环境配置3、属性(properties)4、类型别名(typeAliases)5、设置6、其他配置7、映射器(mappers)8、作用域(Scope)和生命周期 5、解决属性名和字段名不一致的问题:ResultMap6、日志

6.1 日志工厂6.2 LOG4J 7、分页

7.1 使用limit分页7.2 RowBounds实现分页7.3 分页插件 8、使用注解开发

8.1 面向接口编程8.2使用注解开发8.3 CRUD 9、Lombok10、多对一处理

测试环境搭建按照查询嵌套处理按结果嵌套查询 11、一对多处理

1、搭建环境2.按结果嵌套查询3. 按查询嵌套处理 12、动态SQL

搭建环境IFchoose whensetForeachSQL片段 13、缓存

1. Mybatis缓存2、一级缓存3、二级缓存4、ehcache

1.简介 1.1 什么是Mybatis

https://mybatis.org/mybatis-3/zh/index.html

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

1.2 为什么需要Mybatis

帮助程序员将数据存入到数据库中

传统的jdbc代码太复杂。简化。框架。自动化。

简单易学:本身就很小且简单。没有任何第三方依赖,最简单安装只要两个jar文件+配置几个sql映射文件。易于学习,易于使用。通过文档和源代码,可以比较完全的掌握它的设计思路和实现。灵活:mybatis不会对应用程序或者数据库的现有设计强加任何影响。 sql写在xml里,便于统一管理和优化。通过sql语句可以满足操作数据库的所有需求。解除sql与程序代码的耦合:通过提供DAO层,将业务逻辑和数据访问逻辑分离,使系统的设计更清晰,更易维护,更易单元测试。sql和代码的分离,提高了可维护性。提供映射标签,支持对象与数据库的orm字段关系映射。提供对象关系映射标签,支持对象关系组建维护。提供xml标签,支持编写动态sql。 2、第一个Mybatis程序 2.1 搭建环境

搭建数据库

新建普通maven项目,删src

导入依赖


    
        mysql
        mysql-connector-java
        5.1.47
    
    
    
        org.mybatis
        mybatis
        3.5.2
    
    
        junit
        junit
        4.13
        test
    

2.2 创建一个模块

每个基于 MyBatis 的应用都是以一个 SqlSessionFactory 的实例为核心的。SqlSessionFactory 的实例可以通过 SqlSessionFactoryBuilder 获得。而 SqlSessionFactoryBuilder 则可以从 XML 配置文件或一个预先配置的 Configuration 实例来构建出 SqlSessionFactory 实例。

从 XML 文件中构建 SqlSessionFactory 的实例非常简单,建议使用类路径下的资源文件进行配置。

1.resource文件下配置mybatis-config.xml




    
        
            
            
                
                
                
                
            
        
    
    
        
    

2.编写工具类

//sqlSessionFactory----->sqlSession(类比preparedStatement)
public class MybatisUtil {
    private static SqlSessionFactory sqlSessionFactory = null;
    static {
        try {
            //获取sqlSessionFactory对象
            String resource = "mybatis-config.xml";
            InputStream inputStream = Resources.getResourceAsStream(resource);
            sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
        } catch (IOException e) {
            e.printStackTrace();
        }

    }
    
    //既然有了 SqlSessionFactory,顾名思义,我们可以从中获得 SqlSession 的实例。
    // SqlSession 提供了在数据库执行 SQL 命令所需的所有方法。
    // 你可以通过 SqlSession 实例来直接执行已映射的 SQL 语句。
    public static SqlSession getsqlSession(){
        return sqlSessionFactory.openSession();
    }

}
2.3 编写代码

实体类

public class User {
    private int id;
    private String name;
    private String pwd;

    public User() {
    }

    public User(int id, String name, String pwd) {
        this.id = id;
        this.name = name;
        this.pwd = pwd;
    }

    public int getId() {
        return id;
    }

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

    public String getName() {
        return name;
    }

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

    public String getPwd() {
        return pwd;
    }

    public void setPwd(String pwd) {
        this.pwd = pwd;
    }
}

Mapper接口(Dao)

List getUserList();

Mapper.xml(Dao实现类)





    
        select * from mybatis.user where id = #{id}

id:就是对应的namespace中的方法名

resultType:Sql语句执行的返回值

parameterType:参数类型

编写测试

//增删改需要提交事务
@Test
public void addUser(){
    SqlSession sqlSession = MybatisUtil.getsqlSession();
    UserMapper mapper = sqlSession.getMapper(UserMapper.class);
    mapper.addUser(new User(4,"haha","123"));
    //提交事务
    sqlSession.commit();
    sqlSession.close();

}
3、Insert

    insert into mybatis.user (id, name, pwd) values (#{id},#{name},#{pwd})

4、update

    update mybatis.user
    set name = #{name},pwd = #{pwd}
    where id = #{id};

5、delete

    delete
    from mybatis.user
    where id = #{id};

6、万能的Map

    insert into mybatis.user(id,pwd) values (#{userid},#{password})

@Test
public void addUser2(){
    SqlSession sqlSession = MybatisUtil.getsqlSession();
    UserMapper mapper = sqlSession.getMapper(UserMapper.class);
    Map map = new HashMap<>();
    map.put("userid",5);
    map.put("password","222233");
    mapper.addUser2(map);
    //提交事务
    sqlSession.commit();
    sqlSession.close();

}

7、模糊查询

2、或者指定实体类的包,mybatis会在包下搜索需要的JavaBean。类名首字母小写。


    

 resultMap 元素是 MyBatis 中最重要最强大的元素。它可以让你从 90% 的 JDBC ResultSets 数据提取代码中解放出来,并在一些情形下允许你进行一些 JDBC 不支持的操作。

  • 之前你已经见过简单映射语句的示例,它们没有显式指定 resultMap。比如:

     MyBatis 会在幕后自动创建一个 ResultMap,再根据属性名来映射列到 JavaBean 的属性上。如果列名和属性名不能匹配上,可以在 SELECT 语句中设置列别名(这是一个基本的 SQL 特性)来完成匹配。 
    
        select * from user limit #{startIndex},#{pageSize}
    
    @Test
        public void getUserByLimit(){
            SqlSession sqlSession = MybatisUtil.getsqlSession();
            UserMapper mapper = sqlSession.getMapper(UserMapper.class);
            Map map = new HashMap();
            map.put("startIndex",0);
            map.put("pageSize",2);
            List userByLimit = mapper.getUserByLimit(map);
            for (User user : userByLimit) {
                System.out.println(user);
            }
            sqlSession.close();
        }
    
    7.2 RowBounds实现分页
    List getUserByRowBounds();
    
    
        select * from teacher where id = #{tid}
    
    
    按结果嵌套查询

    第二种:select s.id,s.name,t.name from student s,teacher t where s.tid=t.id

    
        select s.id sid,s.name sname,t.name tname
        from student s,teacher t
        where s.tid=t.id
    
    
        
        
        
            
        
    
    
    11、一对多处理 1、搭建环境

    实体类

    @Data
    public class Student {
        private int id;
        private String name;
        //学生关联一个老师
        private int tid;
    }
    
    @Datapublic class Teacher {    private int id;    private String name;    //一个老师拥有多个学生    private List students;}
    
    2.按结果嵌套查询
    
        select * from teacher where id = #{tid}
    
    
        
    
    
        select * from blog where 1=1
        
            and title = #{title}
        
        
            and author = #{author}
        
    
    
    @Testpublic void queryBlogIF(){    SqlSession sqlSession = MybatisUtil.getsqlSession();    BlogMapper mapper = sqlSession.getMapper(BlogMapper.class);    HashMap hashMap = new HashMap();    hashMap.put("title","Java");    hashMap.put("author","狂神说");    List blogs = mapper.queryBlogIF(hashMap);    for (Blog blog : blogs) {        System.out.println(blog);    }    sqlSession.close();}
    
    choose when
    
    
    @Test
    public void queryBlogForeach(){
        SqlSession sqlSession = MybatisUtil.getsqlSession();
        BlogMapper mapper = sqlSession.getMapper(BlogMapper.class);
        HashMap map = new HashMap();
        ArrayList ids = new ArrayList<>();
        ids.add(1);
        map.put("ids",ids);
        List blogs = mapper.queryBlogForeach(map);
        for (Blog blog : blogs) {
            System.out.println(blog);
        }
        sqlSession.close();
    }
    
    SQL片段
    
        
            title = #{title},
        
        
            author = #{author},
        
    
    
        update blog
        
            
        
            where id = #{id}
    
    

    动态SQL就是在拼接SQL语句

    建议:

    先在MySQL中写出完整SQL,再去对应修改为动态SQL实现通用即可

    13、缓存 1. Mybatis缓存

    2、一级缓存

    测试步骤:

    1.开启日志

    2.测试在一个session中查询两次相同记录

    3.查看日志输出

    缓存失效情况:

    1.查询不同东西

    2.增删改操作,可能会改变原来的数据,所以必定刷新缓存

    3.查询不同的Mapper.xml

    4.手动清理缓存

    sqlSession.clearCache();//手动清理
    

    小结:一级缓存默认开启,只在一次SqlSession中有效,也就是拿到连接到关闭连接这个区间段

    3、二级缓存

    要启用全局的二级缓存,只需要在你的 SQL 映射文件中添加一行:

    
    

    这个更高级的配置创建了一个 FIFO 缓存,每隔 60 秒刷新,最多可以存储结果对象或列表的 512 个引用,而且返回的对象被认为是只读的,因此对它们进行修改可能会在不同线程中的调用者产生冲突。

    可用的清除策略有:

    LRU – 最近最少使用:移除最长时间不被使用的对象。FIFO – 先进先出:按对象进入缓存的顺序来移除它们。SOFT – 软引用:基于垃圾回收器状态和软引用规则移除对象。WEAK – 弱引用:更积极地基于垃圾收集器状态和弱引用规则移除对象。

    默认的清除策略是 LRU。

    步骤:

    1.开启全局缓存

    
    

    2.在要使用二级缓存中的Mapper中开启

    
    

    3.测试

    ​ 问题:只写标签,需要将实体类序列化!

    ​ readOnly默认为false,只读不报错,可读写的缓存会通过序列化返回缓存对象的拷贝,此时需要实体类实现Serializable接口或配置 readonly=“true”

    小结

    只要开启了二级缓存,在同一个Mapper下就有效

    所有的数据都会先放在一级缓存中

    只有当会话提交或关闭的时候,才会提交到二级缓存中

    查找顺序:先看二级缓存中有没有,再看一级缓存中有没有,再查询数据库

    4、ehcache

    ehcache是一种广泛使用的开源Java分布式操作,主要面向通用缓存

    1.导包

    
        org.mybatis.caches
        mybatis-ehcache
        1.2.1
    
    

    2.在mapper中指定使用ehcache缓存实现

    
    

    3.配置文件ehcache.xml

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

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

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