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

Mybatis学习笔记(跟学狂神说)

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

Mybatis学习笔记(跟学狂神说)

Mybatis 一. 相关概念
  • JDBC:Java Database Connectivity,Java程序访问数据库的标准接口。
  • Controller层:接收用户的请求,把用户的请求转发给Service层做;
  • Service层:业务层,调用Dao层
  • Dao层
二. 第一个Mybatis程序 1. 搭建环境
  1. 搭建数据库

    MySQL存在服务启动失败的问题,用如下解决办法:

    [外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-HqSaXEpu-1652962814269)(asserts/image-20211016161439458.png)]

    若出现以下错误表示密码错误:

    [外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-bAk2cC06-1652962814272)(asserts/20191102155120683.png)]

    更改密码方法如下:

    1. 设置my.ini文件,在[mysqlId]下方添加 skip-grant-tables,表示连接数据库不需要密码
    2. 终端输入mysql -uroot -p,密码直接回车;
    3. update user set authentication_string = password('xxxxxx')  where user = 'root' ;
    4. 修改my.ini,删除 skip-grant-tables 即可。
    
    CREATE DATABASE `mybatis`;
    
    USE `mybatis`;
    
    CREATE TABLE `user`(
    	`id` INT(10) NOT NULL PRIMARY KEY,
    	`name` VARCHAr(30) DEFAULT NULL,
    	`pwd` VARCHAr(30) DEFAULT NULL
    );
    
    INSERT INTO `user`(`id`, `name`, `pwd`) VALUES
    (1,'Alice','123456'),
    (2,'Job','123456'),
    (3,'Lily','123456')
    
  2. 添加依赖

    
        
            
            
                mysql
                mysql-connector-java
                5.1.47
            
            
            
                org.mybatis
                mybatis
                3.5.6
            
            
            
                junit
                junit
                4.12
            
    
        
    
2. 创建一个模块
  • 编写mybatis核心配置文件

    
    
    
    
    
        
        
            
                
                
                    
                    
                    
                    
                
            
        
    
    
    
  • 编写mybatis工具类

    在src/main/java下建立com.wjy.utils包,创建java文件MybatisUtils

    public class MybatisUtils {
        private static SqlSessionFactory sqlSessionFactory;
    
        static {
            //使用mybatis的第一步:获取SessionFactory对象
            String resource = "mybatis-config.xml"; //获取资源,static初始就加载好
            try {
                //输入流
                InputStream inputStream = Resources.getResourceAsStream(resource);
                //通过SqlSessionFactoryBuilder将sqlSessionFactory加载进去
                sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    
        //既然有了 SqlSessionFactory,顾名思义,我们可以从中获得 SqlSession 的实例。
        // SqlSession 提供了在数据库执行 SQL 命令所需的所有方法。你可以通过 SqlSession 实例来直接执行已映射的 SQL 语句。
        public static SqlSession getsqlSession() {
            return sqlSessionFactory.openSession();
        }
    }
    
    3. 编写代码
    • 实体类

      在com.wjy包下创建pojo包,写实体类

      package com.wjy.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 String getName() {
              return name;
          }
      
          public String getPwd() {
              return pwd;
          }
      
          public void setId(int id) {
              this.id = id;
          }
      
          public void setName(String name) {
              this.name = name;
          }
      
          public void setPwd(String pwd) {
              this.pwd = pwd;
          }
      
          @Override
          public String toString() {
              return "User{" +
                      "id=" + id +
                      ", name='" + name + ''' +
                      ", pwd='" + pwd + ''' +
                      '}';
          }
      }
      
    • Dao接口

      package com.wjy.dao;
      import com.wjy.pojo.User;
      import java.util.List;
      
      public class UseerDaoImpl implements UserDao{
          public List getUserList(){
              //执行SQL
              String sql = "select * from mybatis.user";
              //结果集 ResultSet
          }
      }
      
    • 接口实现类由原来的UserDaoImpl在转变为一个Mapper文件

      
      
      
      
          
          
              select * from mybatis.user
              where name like "%"#{value}"%"
      
      
      四. 配置解析 1. 核心配置文件
      • mybatis-config.xml
      • MyBatis 的配置文件包含了会深深影响 MyBatis 行为的设置和属性信息
      configuration(配置)
      properties(属性)
      settings(设置)
      typeAliases(类型别名)
      typeHandlers(类型处理器)
      objectFactory(对象工厂)
      plugins(插件)
      environments(环境配置)
      environment(环境变量)
      transactionManager(事务管理器)
      dataSource(数据源)
      databaseIdProvider(数据库厂商标识)
      mappers(映射器)
      
      2. 环境配置(environments)
      • Mybatis可以配置多个环境,但每个 SqlSessionFactory 实例只能选择一种环境。

      environments 元素定义了如何配置环境。

      默认transactionmanager为JDBC, datasource为POOLED

      
        
          
          
            
          
          
            
            
            
            
          
        
          
        
            
            
            	
        
      
      
      3. 属性(properties)

      我们可以通过properties属性来实现引用配置文件

      在xml中,所有的标签都可以规定其顺序

      在resources文件夹中建立property配置文件来配置数据库

      driver = com.mysql.jdbc.Driver
      url = jdbc:mysql://localhost:3306/mybatis?userSSL=true&useUnicode=true&characterEncoding=UTF8
      username = root
      password = xxx
      
      
      
      
      • 可以直接引入外部文件
      • 可以在核心配置文件中增加一些属性配置
      • 如果properties文件和核心配置文件的标签中有同一个字段,优先使用外部配置文件。
      4. 类型别名(typeAliases)
      • 类型别名可为 Java 类型设置一个缩写名字

      • 它仅用于 XML 配置,意在降低冗余的全限定类名书写

        方式一:适用于实体类比较少的情况

        
            
                
            
        

        方式二:可以指定一个包名,MyBatis 会在包名下面搜索需要的 Java Bean

        扫描实体类的包,它的默认别名为小写字母的别名

        适用于实体类十分多的情况

        
                
        
        

        方式三:通过注解指定别名

        @Alias("author")
        public class Author {
            ...
        }
        
        5. 映射器(mappers)

      MapperRegistry: 注册绑定我们的Mapper文件;

      • 方式一:

        
            
        
        
      • 方式二:使用class文件绑定注册

        
            
        
        
      • 方式三:使用扫描包进行注入绑定

        
        
        
            
        
        

        方式二和方式三的注意点:

        • 接口和他的Mapper配置文件必须同名
        • 接口和他的Mapper配置文件必须在同一个包中
      五. 解决属性名和字段名不一致的问题

      数据库的字段

      [外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-4acTEC8I-1652962814274)(asserts/image-20211017154721071-16344568445151.png)]

      实体类:

      public class User {
          private int id;
          private String name;
          private String password;
      }
      

      测试出现的问题:

      [外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-6fDb6AkA-1652962814275)(asserts/image-20211017154756321-16344568939202.png)]

      解决方法:起别名

      • as起别名

        
                select * from mybatis.user where id = #{id}
            
        
        
        6六. 分页

        为什么要分页?

        • 减少数据的处理量
        使用limit分页
        语法:SELECT * from user limit startIndex,pageSize;//从第i行开始往后的n行
        SELECt * from user limit i;//从头开始共i行
        
        1. 接口

          //分页
          List getUserByLimit(Map map);
          
        2. Mapper.xml

          #{startIndex},#{pageSize}中对应map中的key

          
          
              select * from mybatis.user limit #{startIndex},#{pageSize}
          
          
        3. 测试

          @Test
          public void getUserByLimit(){
              SqlSession sqlSession = MybatisUtils.getsqlSession();
              UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
          
              HashMap map = new HashMap();
          
              map.put("startIndex",1);
              map.put("pageSize",3);
          
              List userList = userMapper.getUserByLimit(map);
          
              for(User user : userList){
                  System.out.println(user);
              }
              sqlSession.close();
          }
          
        MybatisPlus 一. 快速入门
        1. 创建数据库
        CREATE DATABASE `mybatis_plus`;
        
        use `mybatis_plus`;
        
        CREATE TABLE `user`
        (
        	`id` BIGINT(20) NOT NULL COMMENT '主键ID',
        	`name` VARCHAr(30) NULL DEFAULT NULL COMMENT '姓名',
        	`age` INT(11) NULL DEFAULT NULL COMMENT '年龄',
        	`email` VARCHAr(50) NULL DEFAULT NULL COMMENT '邮箱',
        	PRIMARY KEY (`id`)
        );
        
        INSERT INTO user (id, name, age, email) VALUES
        (1, 'Jone', 18, 'test1@baomidou.com'),
        (2, 'Jack', 20, 'test2@baomidou.com'),
        (3, 'Tom', 28, 'test3@baomidou.com'),
        (4, 'Sandy', 21, 'test4@baomidou.com'),
        (5, 'Billie', 24, 'test5@baomidou.com');
        
        1. 创建springboot项目,导入依赖

          
          
              mysql
              mysql-connector-java
              8.0.25
          
          
          
              org.projectlombok
              lombok
              1.18.20
          
          
          
              com.baomidou
              mybatis-plus-boot-starter
              3.4.3
          
          
        2. 编写配置文件,导入数据库

          #mysql 8
          spring.datasource.name=root
          spring.datasource.password=wang92697.
          spring.datasource.url=jdbc:mysql://localhost:3306/mybatis_plus?useSSL=true&useUnicode=true&characterEncoding=UTF-8&serverTimezone=GMT%22B8
          spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
          
        3. 编写代码

          • pojo
          • mapper接口
          • 使用
        二. 乐观锁

        当要更新一条记录的时候,希望这条记录没有被别人更新
        乐观锁实现方式:

        • 取出记录时,获取当前version
        • 更新时,带上这个version
        • 执行更新时, set version = newVersion where version = oldVersion
        • 如果version不对,就更新失败
        乐观锁:1. 先查询,获得版本号version = 1
        --A
        update user set name = "wjy", version = version + 1
        where id = 2 and version = 1
        
        --B线程抢先完成,version = 2, A线程更新失败
        update user set name = "wjy", version = version + 1
        where id = 2 and version = 1
        
        1. 数据库增加version字段

          use `mybatis_plus`;
          
          alter table `user` add column `version` int(10) DEFAULT(1);
          
        2. 实体类增加对应字段

          @Version//乐观锁Version注解
          private Integer version;
          
        3. 注册组件

          添加config包,在下面创建MybatisPlusConfig

          //自动管理事务
          @EnableTransactionManagement
          @Configuration //配置类
          @MapperScan("com.wjy.mapper")
          public class MybatisPlusConfig {
              @Bean
              public MybatisPlusInterceptor mybatisPlusInterceptor() {
                  MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();
                  interceptor.addInnerInterceptor(new OptimisticLockerInnerInterceptor());
                  return interceptor;
              }
          }
          
        4. 测试

          @Test
          public void testOptimisticLocker2(){
              //oldversion = 2 version = 2
              User user = userMapper.selectById(2L);
              user.setName("wang");
          
              //version = 2
              User user2 = userMapper.selectById(2L);
              user2.setName("jingyu");
              userMapper.updateById(user2);//更新后,version = 3
          
              //oldversion = 2, version != oldversion,更新失败
              userMapper.updateById(user);
          }
          
        三. 查询操作

        查询批量用户

        @Test
        public void testSelectBatchByIds(){
            List users = userMapper.selectBatchIds(Arrays.asList(1,2,3,4));
            users.forEach(System.out::println);
        }
        

        条件查询map

        @Test
        public void testSelectByMap(){
            HashMap map = new HashMap<>();
            //自定义要查询的条件
            map.put("age",24);
            map.put("version",1);
            List users = userMapper.selectByMap(map);
            users.forEach(System.out::println);
        }
        
        四. 分页查询
        1. 定义拦截器组件

          @Bean
          public MybatisPlusInterceptor mybatisPlusInterceptor() {
              MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();
              //分页插件
              interceptor.addInnerInterceptor(new PaginationInnerInterceptor(DbType.H2));
              return interceptor;
          }
          
        2. 使用page对象

          @Test
          public void testPage(){
              //参数1:当前页;参数2:页面的数量
              Page page = new Page<>(1,3);
              userMapper.selectPage(page, null);
              page.getRecords().forEach(System.out::println);
              System.out.println(page.getTotal());
          }
          

          page对象的方法:

          [外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-Zh41ZYVQ-1652962814278)(asserts/image-20211023225647987.png)]

        五. 删除操作
        //通过id删除用户
        userMapper.deleteById(id);
        //通过id批量删除用户
        userMapper.deleteBatchIds(Arrays.asList(1,2,3));
        //通过map删除用户
        new HashMap map = new HashMap<>();
        map.put("name",Alice);
        userMapper.deleteByMap(map);
        
        1. 逻辑删除

        物理删除:直接从数据库中删除

        逻辑删除:在数据库中没有被移除,而是通过一个变量来让他失效。 deleted = 0 => deleted = 1

        逻辑删除只对自动注入的sql起效:

        • 插入: 不作限制

        • 查找: 追加where条件过滤掉已删除数据,且使用 wrapper.entity 生成的where条件会忽略该字段

          select id,name,deleted from user where deleted=0

        • 更新: 追加where条件防止更新到已删除数据,且使用 wrapper.entity 生成的where条件会忽略该字段

        • 删除: 转变为 更新 update user set deleted=1 where id = 1 and deleted=0

        字段类型支持说明:

        • 支持所有数据类型(推荐使用 Integer,Boolean,LocalDateTime)
        • 如果数据库字段使用datetime,逻辑未删除值和已删除值支持配置为字符串null,另一个值支持配置为函数来获取值如now()
        1. 数据库增加deleted属性
        use `mybatis_plus`;
        
        alter table `user` add column `deleted` int(1) DEFAULT(0);
        
        1. 实体类中增加deleted字段,并注释为逻辑删除
        @TableLogic //逻辑删除
        private Integer deleted;
        
        1. 测试
        @Test
        public void LogicDeleted(){
            userMapper.deleteById(6L); //实际上是更新操作,deleted = 1
        }
        
        六. 条件构造器

        条件构造器主要应用于复杂的sql查询

        • eq(colume, val):等于
        • ge(colume, val):大于等于
        • isNotNull(column):不为空
        • isNull(column):为空
        • between(column, val1, val2):在val1~val2之间
        • notBetween(column, val1, val2):不在val1~val2之间

        模糊查询:

        • like(column,val):包含val的column
        • notLike(column,val):不包含val的column
        • likeRight(column,val)/likeLeft(column,val):左匹配%x,右匹配x%
        • inSql(column,val):val可以写成一个sql语句,用于子查询(多表查询的一种)

        userMapper下的查询:

        [外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-Du6bRE9W-1652962814280)(asserts/image-20211024115947873.png)]

        • selectList:查询符合条件的用户列表,以用户类型返回
        • selectPage:查询当前页的用户列表,用page.getRecords()来查询
        • selectCount:查询用户结果数
        • selectOne:查询一个符合条件的用户
        • selectMaps:查询符合条件的用户列表,以map对象返回,也可也i使用forEach进行遍历

        测试:

        @Test
        public void test4(){
            QueryWrapper queryWrapper = new QueryWrapper<>();
            //id 在子查询中查出来(多表查询)
            queryWrapper.inSql("id", "select id from user_test where number = 32");
            userMapper.selectList(queryWrapper).forEach(System.out::println);
        }
        
        //模糊查询
        @Test
        public void test3(){
            QueryWrapper queryWrapper = new QueryWrapper<>();
            queryWrapper
                    .notLike("name","j")
                    .likeRight("email","t");//t%
            List> maps = userMapper.selectMaps(queryWrapper);
            maps.forEach(System.out::println);
        }
        
        七. 配置日志
        #配置日志
        mybatis-plus.configuration.log-impl=org.apache.ibatis.logging.stdout.StdOutImpl
        
转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/919354.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

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

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