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

狂神说Mybatis课程笔记

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

狂神说Mybatis课程笔记

文章目录

1. 第一个Mybatis程序

1.1 搭建环境1.2 创建一个模块1.3 编写代码1.4 测试 2. CURD(增删改查)

2.1 namespace2.2 Select、insert、update、delete2.3 分析错误2.4 使用Map传递参数2.5 模糊查询 3. 配置解析

3.1 核心配置文件3.2 环境配置(environments)3.3 属性(Properties)3.4 类型别名(typeAliases)3.5 设置(settings)3.6 映射器(mappers)3.7 声明周期和作用域 4. 解决属性名和字段名不一致的问题

4.1 ResultMap 5. 日志

5.1 日志工厂5.2 Log4j 6. 分页

6.1 Limit分页6.2 RowBounds分页 7. 使用注解开发8. Lombok9. 多对一处理

复杂查询环境搭建按照结果嵌套处理按照查询嵌套处理回顾MySQL 10. 一对多处理

按照结果嵌套处理按照查询嵌套处理小结 11. 动态SQL

搭建环境IF语句Choose语句trim(Where,set)SQL片段Foreach 12. 缓存(了解)

12.1 简介12.2 Mybatis缓存12.3 一级缓存12.4 二级缓存12.5 缓存原理12.6 自定义缓存-ehcache 13. 29道练习题实战

1. 第一个Mybatis程序

Mybatis3中文文档:https://mybatis.org/mybatis-3/zh/index.html

** 思路:搭建环境、导入mybatis、编写代码、测试。**

1.1 搭建环境
**搭建数据库**
CREATE DATAbase `mybatis`;

USE `mybatis`;

CREATE TABLE `user`(
   `id` INT(20) NOT NULL PRIMARY KEY,
   `name` VARCHAR(30) DEFAULT NULL,
   `pwd` VARCHAR(30) DEFAULT NULL
)ENGINE=INNODB DEFAULT CHARSET=utf8;

INSERT INTO `user`(`id`,`name`,`pwd`) VALUES
(1,'张三','123456'),(2,'赵四','123456'),(3,'王五','123456')
**新建项目**   
新建一个maven项目,删除src文件夹,导入依赖jar包(mysql、mybatis、junit)
    

        
            mysql
            mysql-connector-java
            8.0.28
        

        
            org.mybatis
            mybatis
            3.5.2
        

        
            junit
            junit
            4.13.2
            test
        
    
1.2 创建一个模块
**在resource文件夹下,创建mybatis-config.xml文件,编写mybatis的核心配置文件**



    
        
            
            
                
                
                
                
            
        
    

    
        
    

编写mybatis工具类 (Java.com.kuang.utils.MybatisUtils)

//工具类,sqlSessionFactory
public class MybatisUtils {

    private static SqlSessionFactory sqlSessionFactory;
    static {
        try {
            //使用mybatis的第一步:获取sqlSessionFactory对象
            String resource = "mybatis-config.xml";
            InputStream inputStream = Resources.getResourceAsStream(resource);
            sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static SqlSession getSqlSession(){
        return sqlSessionFactory.openSession();
    }
}
1.3 编写代码

实体类 (java.com.kuang.pojo.User)按照创建的mybatis数据的表User,创建实体类

package com.kuang.pojo;
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;
    }

    @Override
    public String toString() {
        return "User{" +
                "id=" + id +
                ", name='" + name + ''' +
                ", pwd='" + pwd + ''' +
                '}';
    }
}

Dao接口

package com.kuang.dao;

import com.kuang.pojo.User;

import java.util.List;

public interface UserDao { // 或者 UserMapper
    List getUserList();
}

接口实现类由原来的UserDaoImpl转化为一个Mapper配置文件(userMapper.xml)






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


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

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

    
        delete from mybatis.user where id = #{id};
    
    测试
  @Test
    public void getUserById(){
        SqlSession sqlSession = MybatisUtils.getSqlSession();
        UserMapper mapper = sqlSession.getMapper(UserMapper.class);
        User user = mapper.getUserById(1);
        System.out.println(user);

        sqlSession.close();
    }

    @Test
    public void addUser(){
        SqlSession sqlSession = MybatisUtils.getSqlSession();
        UserMapper mapper = sqlSession.getMapper(UserMapper.class);
        int res = mapper.addUser(new User(4,"哈哈","123456"));
        //增删改必须要提交事务
        sqlSession.commit();
        sqlSession.close();
    }

    @Test
    public void updateUser(){
        SqlSession sqlSession = MybatisUtils.getSqlSession();
        UserMapper mapper = sqlSession.getMapper(UserMapper.class);
        mapper.updateUser(new User(4,"呵呵","123123"));
        sqlSession.commit();
        sqlSession.close();
    }

    @Test
    public void deleteUser(){
        SqlSession sqlSession = MybatisUtils.getSqlSession();
        UserMapper mapper = sqlSession.getMapper(UserMapper.class);
        mapper.deleteUser(4);
        sqlSession.commit();
        sqlSession.close();
    }

注意:
测试类中增删改的sql语句中,需要提交事务。

2.3 分析错误

标签匹配不要错resource绑定mapper,需要使用路径 / / / 2.4 使用Map传递参数

假设,实体类或数据库中的表,字段或者参数过多,应当考虑使用map传递参数。

UserMapper.java

    //使用map传递参数,查询用户
    User getUserById2(Map map);
    
    //使用map传递参数,添加用户
    int addUser2(Map map);

UserMapper.xml

    
--         select * from mybatis.user where id = #{id}
        select id,name,pwd as password from mybatis.user where id = #{id}
    

解决方式二:结果集映射

    

        
        
        
    

    
        select * from mybatis.user
    
    测试类
    @Test
    public void getRowBounds(){
        SqlSession sqlSession = MybatisUtils.getSqlSession();

        //RowBounds实现
        RowBounds rowBounds = new RowBounds(1, 2); // 起始值(从零开始),每页显示个数
        //通过java代码层面实现分页
        List userList = sqlSession.selectList("com.kuang.dao.UserMapper.getUserByRowBounds",null,rowBounds);
        for (User user : userList) {
            System.out.println(user);
        }
        sqlSession.close();
    }
7. 使用注解开发

本质:反射机制实现
底层:动态代理

Mybatis详细执行流程:

UserMapper中的接口上编写sql注解:

public interface UserMapper {
    @Select("select * from user")
   List getUserList();
}

核心配置文件mybatis-config.xml中绑定接口:

    
    
        
    

测试:

    @Test
    public void getUserList(){
        SqlSession sqlSession = MybatisUtils.getSqlSession();
        UserMapper mapper = sqlSession.getMapper(UserMapper.class);
        List userList = mapper.getUserList();
        for (User user : userList) {
            System.out.println(user);
        }
        sqlSession.close();
    }

注解增删改查:

1. 更改Mybatis工具类,设置为自动提交事务。

    public static SqlSession getSqlSession(){
        //设置为自动提交事务
        return sqlSessionFactory.openSession(true);
    }

2. 编写接口增加注解:

 //方法存在多个参数的时候,所有的参数前面必须加上@Param("id")注解
    @Select("select * from user where id = #{id}")
    User getUserById(@Param("id") int id);

    //引用型对象则不需要Param
    @Insert("insert into user(id,name,pwd) values(#{id},#{name},#{password})")
    int addUser(User user);

    @Update("update user set name=#{name},pwd=#{password} where id = #{id}")
    int updateUser(User user);

    @Delete("delete from user where id = #{uid}")
    int deleteUser(@Param("uid") int id);

3. 测试类:

【注意】必须将接口注册绑定到MyBatis的核心配置文件中。

关于@Param()注解:

基本类型的参数或者String类型,需要加上。引用类型不需要加。如果只有一个基本类型的话,可以忽略,但是建议都加上。在SQL中引用的就是Param()中设定的属性名,可以自定义。 8. Lombok

1. 在IDEA中安装Lombok插件

2. 在pom.xml文件中添加依赖

        
            org.projectlombok
            lombok
            1.18.10
        

3. 在实体类上加注解即可

@Date:无参构造,get set toString hashCode equals
@AllArgsConstructor  有参构造
@NoArgsConstructor   无参构造
@EqualsAndHashCode
@ToString
@Getter
@Data
@AllArgsConstructor
@NoArgsConstructor
public class User {
    private int id;
    private String name;
    private String password;
}

9. 多对一处理
CREATE TABLE `teacher` (
  `id` INT(10) NOT NULL,
  `name` VARCHAR(30) DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=INNODB DEFAULT CHARSET=utf8

INSERT INTO teacher(`id`, `name`) VALUES (1, '秦老师'); 

CREATE TABLE `student` (
  `id` INT(10) NOT NULL,
  `name` VARCHAR(30) DEFAULT NULL,
  `tid` INT(10) DEFAULT NULL,
  PRIMARY KEY (`id`),
  KEY `fktid` (`tid`),
  CONSTRAINT `fktid` FOREIGN KEY (`tid`) REFERENCES `teacher` (`id`)
) ENGINE=INNODB DEFAULT CHARSET=utf8INSERT INTO `student` (`id`, `name`, `tid`) VALUES ('1', '小明', '1'); 
INSERT INTO `student` (`id`, `name`, `tid`) VALUES ('2', '小红', '1'); 
INSERT INTO `student` (`id`, `name`, `tid`) VALUES ('3', '小张', '1'); 
INSERT INTO `student` (`id`, `name`, `tid`) VALUES ('4', '小李', '1'); 
INSERT INTO `student` (`id`, `name`, `tid`) VALUES ('5', '小王', '1');
复杂查询环境搭建

1. 导入lombok

2. 新建实体类Teacher,Student

@Data
public class Teacher {
    private int id;
    private String name;
}
@Data
public class Student {
    private int id;
    private String name;
    private Teacher teacher;
}

3. 建立Mapper接口

public interface TeacherMapper {
    @Select("select * from teacher where id = #{tid}")
    Teacher getTeacher(@Param("tid") int id);
}
public interface StudentMapper {
}

4. 建立TeacherMapper.xml、StudentMapper.xml文件















5. 在核心配置文件中绑定注册Mapper接口或者文件






    
        
        
    


    
        
    


    
        
            
            
                
                
                
                
            
        
    

    
    
        
        
    


6. 测试查询是否能够成功

    @Test
    public void test(){ //根据id查询老师
        SqlSession sqlSession = MybatisUtils.getSqlSession();
        TeacherMapper mapper = sqlSession.getMapper(TeacherMapper.class);
        Teacher teacher = mapper.getTeacher(1);
        System.out.println(teacher);
        sqlSession.close();
    }

项目结构:

按照结果嵌套处理
    
        select s.id sid, s.name sname,t.name tname
        from student s,teacher t
        where s.tid = t.tid
    

    
        
        
        
            
        
    
 
按照查询嵌套处理

StudentMapper.xml文件配置








    
        select * from teacher where id = #{id}
    


回顾MySQL

子查询 — 按照查询嵌套处理联表查询 — 按照结果嵌套处理 10. 一对多处理

比如:一个老师拥有多个学生,对老师而言,就是一对多的关系。

1. 环境搭建

实体类:

@Data
public class Teacher {
    private int id;
    private String name;
    private List student;
}
@Data
public class Student {
    private int id;
    private String name;
    private int tid;
}
按照结果嵌套处理
    
        select * from mybatis.teacher where id = #{tid}
    

    
        
    

    
        select * from mybatis.blog where 1=1
        
            and title = #{title}
        
        
            and author = #{author}
        
    
    

    
        
    

3. 测试类

    @Test
    public void queryBlogIf(){
        SqlSession sqlSession = MybatisUtils.getSqlSession();
        BlogMapper mapper = sqlSession.getMapper(BlogMapper.class);
        HashMap map = new HashMap();
//        map.put("title","Java如此简单");
        map.put("author","狂神说");
        List blogs = mapper.queryBlogIf(map);
        for (Blog blog : blogs) {
            System.out.println(blog);
        }
    }
Choose语句

Choose:类似switch结构。从上至下判断,满足其中一个条件,自动跳出。上面都不满足,自动执行otherwise语句中的内容。

    
            select * from mybatis.blog
            
                
                    and title = #{title}
                
                
                    and author = #{author}
                
            
        

Set

    
        update mybatis.blog
        
            
                title = #{title},
            
            
                author = #{author}
            
        
        where id = #{id}
    

所谓的动态SQL,本质还是SQL语句,只是在SQL层面,去执行一个逻辑代码。

SQL片段

实现公用代码的复用,对多sql语句共有的语句进行抽取封装。

    使用SQL标签抽取公共的部分
    
        
            and title = #{title}
        
        
            and author = #{author}
        
    
    在需要使用的地方使用include标签引用即可
    

测试类:

    @Test
    public void queryBlogForeach(){
        SqlSession sqlSession = MybatisUtils.getSqlSession();
        BlogMapper mapper = sqlSession.getMapper(BlogMapper.class);
        HashMap map = new HashMap();

        ArrayList ids = new ArrayList();
        ids.add(1);
        ids.add(2);
        ids.add(3);

        map.put("ids",ids);

        List blogs = mapper.queryBlogForeach(map);
        for (Blog blog : blogs) {
            System.out.println(blog);
        }
    }
12. 缓存(了解) 12.1 简介

1. 什么是缓存?

存在内存中的临时数据。将用户经常查询的数据放在缓存(内存)中,用户查询时不需从磁盘上查询,从缓存中查询,从而提高查询效率,解决了高并发系统的性能问题。

2. 为什么使用缓存?

减少和数据库的交互次数,减少系统开销,提高系统效率。

3. 什么样的数据使用缓存?

经常查询并且不经常改变的数据。 12.2 Mybatis缓存

Mybatis系统中默认定义了两级缓存:一级缓存 和 二级缓存。

默认情况下,只有一级缓存开启。(SqlSession级别的缓存,也称为本地缓存)二级缓存需要手动开启和配置,是基于namespace级别的缓存。为了提高扩展性,Mybatis定义了缓存接口Cache,可通过Cache接口自定义二级缓存。 12.3 一级缓存

缓存失效的情况:

    查询不同的东西。增删改操作,可能会改变原来的数据,所以会刷新缓存。查询不同的Mapper.xml。手动清楚缓存。 sqlSession.clearCache();

小结:

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

12.4 二级缓存

步骤:

    开启全局缓存
    
        
    

在要使用二级缓存的Mapper中开启,可以自定义参数

  

小结:

只要开启了二级缓存,在同一个Mapper下就有效。所有的数据都会先放在一级缓存中。只有当会话提交,或者关闭的时候,才会提交到二级缓存中。 12.5 缓存原理

12.6 自定义缓存-ehcache

要在程序中使用ehcache,先要导包。

        
            org.mybatis.caches
            mybatis-ehcache
            1.1.0
        
13. 29道练习题实战

推荐博客:

https://blog.csdn.net/qq_38616503/article/details/107149495?ops_request_misc=%257B%2522request%255Fid%2522%253A%2522164802218216780264043931%2522%252C%2522scm%2522%253A%252220140713.130102334…%2522%257D&request_id=164802218216780264043931&biz_id=0&utm_medium=distribute.pc_search_result.none-task-blog-2allbaidu_landing_v2~default-1-107149495.142v3pc_search_result_control_group,143v4control&utm_term=smbms+mybatis&spm=1018.2226.3001.4187

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

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

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