• Mybatis-Plus的使用


     
     

    1.什么是Mybatis-Plus

      MyBatis-Plus(简称 MP)是一个 MyBatis 的增强工具,在 MyBatis 的基础上只做增强不做改变,为简化开发、提高效率而生。
     

    2.为什么要学习Mybatis-Plus

      我们已经学习过Mybatis这个框架,我们只需要在dao层定义抽象接口,基于Mybatis零实现的特性,就可以实现对数据库的crud操作。
      如下两个接口:
      UserMapper接口
    public interface UserMapper {
        int deleteByPrimaryKey(Long id);
        int insert(User user);
        List<User> selectList();
        User selectByPrimaryKey(Long id);
    }
      OrderMapper接口
    public interface OrderMapper {
     
        int deleteByPrimaryKey(Long id);
        int insert(Order order);
        List<Order> selectList();
        User selectByPrimaryKey(Long id);
    }
      从上面两个业务接口中,我们发现:它们定义了一组类似的crud方法。在业务类型比较多的时候,我们就需要重复的定义这组功能类似的接口方法。如何解决这个问题呢?
      如果使用Mybatis-plus,甚至都不需要任何的xml映射文件或者接口方法注解,只需要让我们定义的抽象接口继承一个公用的BaseMapper接口就能完成dao层的一些基本的通用方法(如crud),做到真正的dao层零实现。
    public interface UserMapper extends BaseMapper<User> {
       //BaseMapper已经实现了基本的通用方法了。如果有需要非通用的操作,才在这里自定义
    }
     

    3.入门示例

    3.1 说明

      1.Mybatis-Plus并没有提供单独的jar包,而是通过Maven(或者gradle)来管理jar依赖。所以需要使用Maven构建项目。
      2.Mybatis-Plus是基于Spring框架实现的,因此使用Mybatis-Plus,必须导入Spring相关依赖。
     

    3.2 准备工作

      先创建好了数据库环境
      建表语句:
      
    CREATE TABLE `tb_user` (
      `id` bigint(20) NOT NULL COMMENT '主键ID',
      `name` varchar(30) DEFAULT NULL COMMENT '姓名',
      `age` int(11) DEFAULT NULL COMMENT '年龄',
      `email` varchar(50) DEFAULT NULL COMMENT '邮箱',
      PRIMARY KEY (`id`)
    )
     

    3.3 配置步骤

    3.3.1 第一步:搭建环境

    1.创建一个Maven项目
    0
    2.配置pom.xml文件
    导入相关依赖,并且配置项目的编码,JDK版本等构建信息
    <
    <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
      <modelVersion>4.0.0</modelVersion>
      <groupId>com.gjs</groupId>
      <artifactId>mybatis-plus-01-start</artifactId>
      <version>1.0</version>
      
      <dependencies>
          <!-- spring依赖 -->
          <dependency>
              <groupId>org.springframework</groupId>
              <artifactId>spring-context</artifactId>
              <version>4.3.20.RELEASE</version>
          </dependency>
    
          <dependency>
              <groupId>org.springframework</groupId>
              <artifactId>spring-jdbc</artifactId>
              <version>4.3.20.RELEASE</version>
          </dependency>
          
          <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-test</artifactId>
            <version>4.3.20.RELEASE</version>
            <scope>test</scope>
        </dependency>
          
          <!-- mybatis-plus -->
        <dependency>
            <groupId>com.baomidou</groupId>
            <artifactId>mybatis-plus</artifactId>
            <version>2.3</version>
        </dependency>
        
        <!-- Mysql 驱动 -->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.47</version>
        </dependency>
        
        <!-- 连接池 -->
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>druid</artifactId>
            <version>1.1.9</version>
        </dependency>
    
        <!-- junit -->
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.12</version>
            <scope>test</scope>
        </dependency>
        
      </dependencies>
      
      <!-- 只要配置了build标签里面的内容,配置后都需要强制更新项目 -->
      <build>
          <plugins>
              <plugin>
                  <groupId>org.apache.maven.plugins</groupId>
                  <artifactId>maven-compiler-plugin</artifactId>
                  <version>3.8.1</version>
                  <configuration>
                      <!-- 设置编码 -->
                      <encoding>utf-8</encoding>
                      <!-- 设置JDK版本 -->
                      <source>1.8</source>
                      <target>1.8</target>
                  </configuration>
              </plugin>
            <!-- 设置安装install命令的时候跳过单元测试 -->
              <plugin>
                  <groupId>org.apache.maven.plugins</groupId>
                  <artifactId>maven-surefire-plugin</artifactId>
                  <version>2.18.1</version>
                  <configuration>
                      <skipTests>true</skipTests>
                  </configuration>
              </plugin>
              
          </plugins>
      </build>
    </project>
     

    3.3.2 第二步:Mybatis-Plus整合Spring

    Mybatis-Plus整合Spring和Mybatis整合Spring差不多,只是会话工厂从org.mybatis.spring.SqlSessionFactoryBean换成com.baomidou.mybatisplus.spring.MybatisSqlSessionFactoryBean
    <?xml version="1.0" encoding="UTF-8"?>
    <beans xmlns="http://www.springframework.org/schema/beans"
        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
        xmlns:context="http://www.springframework.org/schema/context"
        xmlns:tx="http://www.springframework.org/schema/tx"
        xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
            http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.3.xsd
            http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.3.xsd">
        <!-- 1.配置数据源 -->
        <bean name="dataSource" class="com.alibaba.druid.pool.DruidDataSource">
            <property name="driverClassName" value="com.mysql.jdbc.Driver"/>
            <property name="url" value="jdbc:mysql://localhost:3306/mybatis-plus"></property>
              <property name="username" value="root"></property>
               <property name="password" value="1234"></property>
               <!-- 最大连接数 -->
              <property name="maxActive" value="10"></property>
             <!-- 超时毫秒数 -->
               <property name="maxWait" value="30000"></property>
        </bean>
        
        <!-- 2.配置会话工厂 -->
        <bean name="sqlSessionFactory" class="com.baomidou.mybatisplus.spring.MybatisSqlSessionFactoryBean">
            <!-- 指定数据源 -->
            <property name="dataSource" ref="dataSource"/>
        </bean>
        
        <!-- 3.配置映射动态代理对象到spring容器 -->
        <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
            <!-- 指定会话工厂 -->
            <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"/>
            <!-- 指定扫描的映射包 -->
            <property name="basePackage" value="com.gjs.mybatisplus.mapper"/>
        </bean>
        <!-- 4.配置事务管理器 -->
        <bean name="tx" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
            <property name="dataSource" ref="dataSource"></property>
        </bean>
        <tx:annotation-driven transaction-manager="tx"/>
    </beans>
     

    3.3.3 第三步:编写POJO

      使用Mybatis-Plus不使用xml文件,而是基于一组注解来解决实体类和数据库表的映射问题。
    注解
    作用
    @TableName(value="tb_user")
    指定对应的表,表名和类名一致时,可以省略value属性。
    @TableId
    指定表的主键。Value属性指定表的主键字段,和属性名一致时,可以省略。Type指定主键的增长策略。
    @TableField
    指定类的属性映射的表字段,名称一致时可以省略该注解。
     
    package com.gjs.mybatisplus.pojo;
    
    import com.baomidou.mybatisplus.annotations.TableField;
    import com.baomidou.mybatisplus.annotations.TableId;
    import com.baomidou.mybatisplus.annotations.TableName;
    import com.baomidou.mybatisplus.enums.IdType;
    @TableName(value="tb_user")
    public class User {
        /*
        AUTO->`0`("数据库ID自增")
        INPUT->`1`(用户输入ID")
        ID_WORKER->`2`("全局唯一ID")
        UUID->`3`("全局唯一ID")
        NONE-> 4 ("不需要ID")
        */
        @TableId(value="id",type=IdType.AUTO)
        private Long id;
        //如果属性名与数据库表的字段名相同可以不写
        @TableField(value="name")
        private String name;
        @TableField(value="age")
        private Integer age;
        @TableField(value="email")
        private String email;
        public Long getId() {
            return id;
        }
        public void setId(Long id) {
            this.id = id;
        }
        public String getName() {
            return name;
        }
        public void setName(String name) {
            this.name = name;
        }
        public Integer getAge() {
            return age;
        }
        public void setAge(Integer age) {
            this.age = age;
        }
        public String getEmail() {
            return email;
        }
        public void setEmail(String email) {
            this.email = email;
        }
    }

    3.3.4 第四步:编写Mapper接口

    package com.gjs.mybatisplus.mapper;
    
    import org.springframework.stereotype.Repository;
    
    import com.baomidou.mybatisplus.mapper.BaseMapper;
    import com.gjs.mybatisplus.pojo.User;
    
    @Repository
    public interface UserMapper extends BaseMapper<User>{
        
    }

    3.3.5 编写测试类

    package com.gjs.test;
    
    import java.util.List;
    
    import org.junit.Test;
    import org.junit.runner.RunWith;
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.test.context.ContextConfiguration;
    import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
    
    import com.baomidou.mybatisplus.mapper.EntityWrapper;
    import com.gjs.mybatisplus.mapper.UserMapper;
    import com.gjs.mybatisplus.pojo.User;
    
    @RunWith(SpringJUnit4ClassRunner.class)
    @ContextConfiguration(locations="classpath:spring-data.xml")
    public class TestUserMapper {
        @Autowired
        private UserMapper userMapper;
        
        /**
         * 添加
         */
        @Test
        public void insert() {
            try {
                User user=new User();
                user.setName("zhangsan");
                user.setAge(20);
                user.setEmail("zhangsan@163.com");
                Integer insert = userMapper.insert(user);
                System.out.println(insert);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        
        /**
         * 通过id删除
         */
        @Test
        public void deleteById() {
            try {
                Integer count = userMapper.deleteById(1L);
                System.out.println(count);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        /**
         * 通过条件删除
         */
        @Test
        public void deleteByCondition() {
            try {
                //设置条件
                EntityWrapper<User> wrapper=new EntityWrapper<>();
                wrapper.like("name", "%wang%");
                Integer count = userMapper.delete(wrapper);
                System.out.println(count);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        
        /**
         * 更新非空字段,通过id
         */
        @Test
        public void update() {
            User user=new  User();
            user.setName("lisi");
            user.setEmail("lisi@163.com");
            user.setId(2L);
            userMapper.updateById(user);
            
        }
        
        /**
         * 查询所有
         */
        @Test
        public void findAll() {
            //查询条件为空时,查询所有
            List<User> users = userMapper.selectList(null);
            for (User user : users) {
                System.out.println(user.getName());
            }
        }
    }

    4.常用配置

    4.1 实体类全局配置

      如果在配置文件指定实体类的全局配置,那么可以不需要再配置实体类的关联注解。
    <!-- 2.配置会话工厂 -->
        <bean name="sqlSessionFactory" class="com.baomidou.mybatisplus.spring.MybatisSqlSessionFactoryBean">
            <!-- 指定数据源 -->
            <property name="dataSource" ref="dataSource"/>
            <property name="globalConfig">
                <bean class="com.baomidou.mybatisplus.entity.GlobalConfiguration">
                    <!-- 
                        AUTO->`0`("数据库ID自增")
                        INPUT->`1`(用户输入ID")
                        ID_WORKER->`2`("全局唯一ID")
                        UUID->`3`("全局唯一ID")
                        NONE-> 4 ("不需要ID")
                     -->
                    <property name="idType" value="0"></property>
                    <!-- 实体类名与数据库表名的关联规则是,忽略前缀 -->
                    <property name="tablePrefix" value="tb_"></property>
                </bean>
            </property>
        </bean>
    实体类就可以去掉关联的注解了
    package com.gjs.mybatisplus.pojo;
    
    public class User {
        
        private Long id;
        private String name;
        private Integer age;
        private String email;
        public Long getId() {
            return id;
        }
        public void setId(Long id) {
            this.id = id;
        }
        public String getName() {
            return name;
        }
        public void setName(String name) {
            this.name = name;
        }
        public Integer getAge() {
            return age;
        }
        public void setAge(Integer age) {
            this.age = age;
        }
        public String getEmail() {
            return email;
        }
        public void setEmail(String email) {
            this.email = email;
        }
    }

    4.2.插件配置

      Mybatis默认情况下,是不支持物理分页的。默认提供的RowBounds这个分页是逻辑分页来的。
      逻辑分页:将数据库里面的数据全部查询出来后,在根据设置的参数返回对应的记录。(分页是在程序的内存中完成)。【表数据过多时,会溢出】
      物理分页:根据条件限制,返回指定的记录。(分页在数据库里面已经完成)
     
      MybatisPlus是默认使用RowBounds对象是支持物理分页的。但是需要通过配置Mybatis插件来开启。
      配置:
    <!-- 2.配置会话工厂 -->
        <bean name="sqlSessionFactory" class="com.baomidou.mybatisplus.spring.MybatisSqlSessionFactoryBean">
            <!-- 指定数据源 -->
            <property name="dataSource" ref="dataSource"/>
            <property name="globalConfig">
                <bean class="com.baomidou.mybatisplus.entity.GlobalConfiguration">
                    <!-- 
                        AUTO->`0`("数据库ID自增")
                        INPUT->`1`(用户输入ID")
                        ID_WORKER->`2`("全局唯一ID")
                        UUID->`3`("全局唯一ID")
                        NONE-> 4 ("不需要ID")
                     -->
                    <property name="idType" value="0"></property>
                    <!-- 实体类名与数据库表名的关联规则是,忽略前缀 -->
                    <property name="tablePrefix" value="tb_"></property>
                </bean>
            </property>
            <property name="plugins">
                <list>
                    <!-- 分页的支持 -->
                    <bean class="com.baomidou.mybatisplus.plugins.PaginationInterceptor">
                        <!-- 数据库方言  -->
                        <!-- 不同的数据库对sql标准未制定的功能不一样,比如分页,所以需要指定数据库方言 -->
                        <property name="dialectClazz" value="com.baomidou.mybatisplus.plugins.pagination.dialects.MySqlDialect"></property>
                    </bean>
                    <!-- 配置日志输出(SQL语句) -->
                    <bean class="com.baomidou.mybatisplus.plugins.PerformanceInterceptor">
                        <!-- 配置sql语句输出格式,true为折叠,false为平铺,不配默认为false -->
                        <property name="format" value="true"></property>
                    </bean>
                </list>
            </property>
        </bean>
      测试方法:
    /**
         * 分页查询
         */
        @Test
        public void findPage() {
            try {
                List<User> users = userMapper.selectPage(new RowBounds(0, 5), null);
                for (User user : users) {
                    System.out.println(user.getName());
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
     

    5.自定义方法

      MyBatis-Plus只是在MyBatis的基础上做了增强,不做改变。所以MyBatis-Plus定义的基础方法不能满足需求时,可以通过MyBatis的语法定义方法,但最好不要用MyBatis-Plus以及定义的方法名。

     

    6.Service 层

      MyBatis-Plus 不仅提供了持久层的基础通用方法,它还提供了一套业务层的通用方法。
      想要使用这些方法,只需让我们定义的service层的接口继承MyBatis-Plus定义的IService接口,并让实现类继承MyBatis-Plus定义的ServiceImpl类。
     
    public interface UserService extends IService<User>{
        
    }
    @Service
    public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService{
        
    }

    原文链接:https://www.cnblogs.com/gaojinshun/p/14545345.html

     
    作者:ki16
    本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须在文章页面给出原文连接,否则保留追究法律责任的权利。
  • 相关阅读:
    MySQL实战 | 01-当执行一条 select 语句时,MySQL 到底做了啥?
    人人都能看懂的云计算知识科普
    教你用 Python 实现抖音热门表白软件
    Docker中“TERM environment variable not set.”问题
    centos 6.5安装docker
    centos6安装docker,先升级系统内核
    MySQL中一个sql语句包含in优化问题
    阿里云提示ECS服务器存在漏洞处理方法
    yum安装 指定安装目录
    nginx重启报错:nginx: [error] invalid PID number "" in "/run/nginx.pid"
  • 原文地址:https://www.cnblogs.com/gaojinshun/p/14545345.html
Copyright © 2020-2023  润新知