MyBatis-Plus(spring版)学习笔记

 

目录

 

前言

基于尚硅谷杨博超老师讲解的Mybtaisplus(spring版)的学习笔记。
windows系统下的mysql密码是:abc123。
项目地址

从github导入maven项目时,因为我们设置了ignore文件,所以在复制导入的时候,本地是没有src目录的,我们需要自己创建。即src\main\java 和src\main\resources及src\test\java。
在这里插入图片描述


1 MyBatis-Plus简介

1.1 简介

在这里插入图片描述

1.2 特性

在这里插入图片描述

1.3 支持数据库

在这里插入图片描述

1.4 框架结构

在这里插入图片描述

工作原理:扫描实体类,通过反射抽取实体类中的属性,然后再分析我们要操作的表是谁?需要操作的实体类的属性是谁?也就是表中的字段是谁?然后再生成对应的sql语句,然后再注入到mybatis容器中。

1.5 代码及文档地址

在这里插入图片描述

2 入门案例

2.1 开发环境

以maven工程为例,以ssm整合为技术框架。

工具版本
IDE idea 2021.3
JDK JDK1.8
MAVEN maven 3.8.4
MySQL MySQL5.7
Spring 5.3.1
MyBatis-Plus 3.4.3.4

2.2 准备工作

2.2.1 创建maven工程并引入依赖

新建一个maven工程。引入需要的依赖。
注意使用mybatis-plus代替mybatis和spring的依赖。
完整版依赖在项目地址中。此处的依赖仅仅只是为了先构建框架。

<?xml version="1.0" encoding="UTF-8"?>
<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.atguigu.ssm</groupId>
    <artifactId>ssm-integration</artifactId>
    <version>1.0-SNAPSHOT</version>
    <packaging>jar</packaging>

    <dependencies>
        <!--提供大量扩展,提供一些容器实现-->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context</artifactId>
            <version>${spring.version}</version>
        </dependency>
        <!-- Spring 的测试功能 -->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-test</artifactId>
            <version>${spring.version}</version>
        </dependency>

        <!-- 日志 -->
        <dependency>
            <groupId>ch.qos.logback</groupId>
            <artifactId>logback-classic</artifactId>
            <version>1.2.3</version>
        </dependency>

        <!-- MySQL驱动 -->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.3</version>
        </dependency>

        <!-- 数据源连接池 -->
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>druid</artifactId>
            <version>1.0.31</version>
        </dependency>

        <!-- junit5测试类-->
        <dependency>
            <groupId>org.junit.jupiter</groupId>
            <artifactId>junit-jupiter-api</artifactId>
            <version>5.7.0</version>
            <scope>test</scope>
        </dependency>

        <!-- lombok用来简化实体类 -->
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <version>1.16.16</version>
        </dependency>

        <!--MyBatis-Plus的核心依赖-->
        <dependency>
            <groupId>com.baomidou</groupId>
            <artifactId>mybatis-plus</artifactId>
            <version>3.4.3.4</version>
        </dependency>



    </dependencies>
    <properties>
        <maven.compiler.source>8</maven.compiler.source>
        <maven.compiler.target>8</maven.compiler.target>
        <spring.version>5.3.1</spring.version>
    </properties>


</project>

在这里插入图片描述
在这里插入图片描述
在这里插入图片描述

注意

1. MySQL5.7版本的url:
jdbc:mysql://localhost:3306/mybatis_plus?characterEncoding=utf-8&useSSL=false

2. MySQL8.0版本的url:
jdbc:mysql://localhost:3306/mybatis_plus?
serverTimezone=GMT%2B8&characterEncoding=utf-8&useSSL=false

3. 否则运行测试用例报告如下错误:
java.sql.SQLException: The server time zone value 'Öйú±ê׼ʱ¼ä' is unrecognized orrepresents more

2.2.2 物理建模:创建数据库及表

在这里插入图片描述

2.2.3 逻辑建模:创建实体类

[1] lombok插件的使用

简化实体类开发,即我们不需要手动去创建有参和无参构造以及get和set方法还有tostring等。

我们只需要在类上加入注解:在这里插入图片描述
在这里插入图片描述

然后重新进行编译之后就会自动帮助我们创建。
但是如果在一个类上写如此多的注解,我们可以使用一个Data注解来代替上面设置的5 个注解。

注意:data注解中不包括有参构造,但是新增了一个tostring方法,所以说相当于还是代替5个注解。

在这里插入图片描述
这个注解是我们使用最多的。

[2] 创建实体类

这里我们使用lombok插件简化实体类开发。

@Data
public class User {
    private Long id;
    private String name;
    private Integer age;
    private String email;
}

注意此处的id类型是Long类型,不要写成long类型,否则雪花算法不会实现。因为雪花算法要求就是Long。

2.2.4 加入日志配置文件

日志文件对于我们进行调试代码有很好的作用,我们可以使用日志配置文件进行更好的查询到异常问题所在。
注意:配置文件全部放在resources目录下。

logback.xml

<?xml version="1.0" encoding="UTF-8"?>
<configuration debug="false">
    <!--定义日志文件的存储地址 logs为当前项目的logs目录 还可以设置为../logs -->
    <property name="LOG_HOME" value="logs" />
    <!--控制台日志, 控制台输出 -->
    <appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
        <encoder class="ch.qos.logback.classic.encoder.PatternLayoutEncoder">
            <!--格式化输出:%d表示日期,%thread表示线程名,%-5level:级别从左显示5个字符
            宽度,%msg:日志消息,%n是换行符-->
            <pattern>%d{yyyy-MM-dd HH:mm:ss.SSS} [%thread] %-5level %logger{50}
                - %msg%n</pattern>
        </encoder>
    </appender>
    <!-- 日志输出级别 -->
    <root level="DEBUG">
        <appender-ref ref="STDOUT" />
    </root>

    <!-- 根据特殊需求指定局部日志级别 -->
    <logger name="org.springframework.web.servlet.DispatcherServlet" level="DEBUG" />
    <logger name="src/test/java/com/atguigu/mybatisplus/test/MyBatisPlusTest.java" level="DEBUG"/>
</configuration>

2.3 连接数据库

2.3.1 创建jdbc.properties

resources目录下创建jdbc.properties文件。

jdbc.username=root
jdbc.password=abc123
jdbc.url=jdbc:mysql://localhost:13306/mybatis_plus
jdbc.driver=com.mysql.jdbc.Driver

2.3.2 创建Spring配置文件并完成测试所需配置

因为目前我们只是先进行数据库连接的测试,所以我们需要配置的很少。只需要引入jdbc.properties文件和配置数据源既可。

spring-persist

<?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"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
                            http://www.springframework.org/schema/beans/spring-beans.xsd
                            http://www.springframework.org/schema/context
                            https://www.springframework.org/schema/context/spring-context.xsd">
    <!-- 引入jdbc.properties -->
    <context:property-placeholder location="classpath:jdbc.properties"></context:property-placeholder>

    <!-- 配置Druid数据源 -->
    <bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource">
        <property name="driverClassName" value="${jdbc.driver}"></property>
        <property name="url" value="${jdbc.url}"></property>
        <property name="username" value="${jdbc.username}"></property>
        <property name="password" value="${jdbc.password}"></property>
    </bean>
</beans>

2.3.3 创建junit测试类测试

测试类写法有两种。按自己喜好选择。

spring测试类写法1
//    //在spring的环境中进行测试
//@RunWith(SpringJUnit4ClassRunner.class)
指定spring的配置文件
//@ContextConfiguration("classpath:spring-persist.xml")


//spring测试类写法2
@SpringJUnitConfig(locations = {"classpath:spring-persist.xml"})
public class MyBatisPlusTest {

    @Autowired
    private DruidDataSource dataSource;

    Logger logger = LoggerFactory.getLogger(getClass());


    @Test
    public void getConn() throws SQLException {
        DruidPooledConnection connection = dataSource.getConnection();

        logger.debug(connection.toString());

    }

}

执行操作,测试成功。

2.4 spring整合mybatis

2.4.1 创建mybatis的配置文件

在resources下创建mybatis-config.xml。

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration
        PUBLIC "-//MyBatis.org//DTD Config 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-config.dtd">
<!--设置实体类所在包的别名-->
    <typeAliases>
        <package name="com.atguigu.mybatisplus.entity"/>
    </typeAliases>

</configuration>

注意此处不需要设置驼峰式命名,因为mybatisplus就是默认会转换为驼峰式命名。

驼峰式命名
包名:xxxyyyzzz
类名、接口名:XxxYyyZzz
变量名、方法名:xxxYyyZzz
常量名:XXX_YYY_ZZZ

2.4.2 创建mapper接口

public interface UserMapper  {
    /**
     * 查询所有用户信息
     * @return
     */

    List<User> getAllUser();
}

2.4.3 创建mapper映射文件

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
        PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.atguigu.mybatisplus.mapper.TestMapper">

    <!-- List<User> getAllUser();-->
    <select id="getAllUser" resultType="user">
        select id,name,age,email from user
    </select>

</mapper>

2.4.4 完善spring配置文件

<?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"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
                            http://www.springframework.org/schema/beans/spring-beans.xsd
                            http://www.springframework.org/schema/context
                            https://www.springframework.org/schema/context/spring-context.xsd">
    <!-- 引入jdbc.properties -->
    <context:property-placeholder location="classpath:jdbc.properties"></context:property-placeholder>

    <!-- 配置Druid数据源 -->
    <bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource">
        <property name="driverClassName" value="${jdbc.driver}"></property>
        <property name="url" value="${jdbc.url}"></property>
        <property name="username" value="${jdbc.username}"></property>
        <property name="password" value="${jdbc.password}"></property>
    </bean>

    <!--整合mybatis-->
    <bean id="sessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
        <!--指定mybatis配置文件-->
        <property name="configLocation" value="classpath:mybatis-config.xml"/>
        <!--指定mapper.xml-->
        <property name="mapperLocations" value="classpath:mappers/*Mapper.xml"/>
        <!--装配数据源-->
        <property name="dataSource" ref="dataSource"/>
    </bean>

<!--配置扫描mapper接口到ioc容器-->
    <bean id="mapperScannerConfigurer" class="org.mybatis.spring.mapper.MapperScannerConfigurer">
        <property name="basePackage" value="com.atguigu.mybatisplus.mapper"/>
    </bean>

</beans>

2.4.5 测试

 @Autowired
    private UserMapper userMapper;

    @Test
    public void testUserMapper(){
        List<User> UserList = userMapper.getAllUser();
        for (User user:UserList){
            System.out.println("user = " + user);
        }
    }

最开始进行测试出现错误

org.apache.ibatis.binding.BindingException: Invalid bound statement (not found): com.atguigu.mybatisplus.mapper.UserMapper.getAllUser

出现此错误的原因是usermapper.xml文件中命名空间写错了。
检查xml文件所在package名称是否和Mapper interface所在的包名

<mapper namespace="com.atguigu.mybatisplus.mapper.UserMapper">

修改成功后测试通过。
在这里插入图片描述

2.5 使用mybatisplus

2.5.1 修改spring配置文件

使用的是MybatisSqlSessionFactoryBean
经观察,目前bean中配置的属性和SqlSessionFactoryBean一致
MybatisSqlSessionFactoryBean是在SqlSessionFactoryBean的基础上进行了增强
即具有SqlSessionFactoryBean的基础功能,又具有MyBatis-Plus的扩展配置
具体配置信息地址:https://baomidou.com/pages/56bac0/#%E5%9F%BA%E6%9C%AC%E9%
85%8D%E7%BD%AE

spring整合Mybatis

    <!--整合mybatis-->
    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
        <!--指定mybatis配置文件-->
        <property name="configLocation" value="classpath:mybatis-config.xml"/>
        <!--指定mapper.xml-->
        <property name="mapperLocations" value="classpath:mappers/*Mapper.xml"/>
        <!--装配数据源-->
        <property name="dataSource" ref="dataSource"/>
    </bean>

加入mybatisplus

<!--使用mybatisplus-->
    <bean id="mybatisSqlSessionFactoryBean" class="com.baomidou.mybatisplus.extension.spring.MybatisSqlSessionFactoryBean">
        <!--指定mybatis配置文件-->
        <property name="configLocation" value="classpath:mybatis-config.xml"/>
        <!--指定mapper.xml-->
        <property name="mapperLocations" value="classpath:mappers/*Mapper.xml"/>
        <!--装配数据源-->
        <property name="dataSource" ref="dataSource"/>
    </bean>

2.5.2 修改mapper接口

未修改前


public interface UserMapper  {
    /**
     * 查询所有用户信息
     * @return
     */


    List<User> getAllUser();
}

加入Mybatisplus后


//使用mybatisplus
public interface UserMapper extends BaseMapper {
  
}

BaseMapper是MyBatis-Plus提供的基础mapper接口,泛型为所操作的实体类型,其中包含
CRUD的各个方法,我们的mapper继承了BaseMapper之后,就可以直接使用BaseMapper所提
供的各种方法,而不需要编写映射文件以及SQL语句,大大的提高了开发效率

2.5.3 测试

注意此时出现错误:

Caused by: java.lang.NoClassDefFoundError: org/springframework/dao/support/DaoSupport

原因:
缺少 spring-jdbc 依赖

 <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-jdbc</artifactId>
            <version>${spring.version}</version>
        </dependency>

在pom.xml中加入依赖后重新进行测试。

  @Autowired
    private UserMapper userMapper;

    //使用mybatisplus
    @Test
    public  void testMybatisPlus(){
        //根据id查询用户信息
        System.out.println(userMapper.selectById(1));
    }

测试通过。

3 基本的CRUD

3.1 BaseMapper

MyBatis-Plus中的基本CRUD在内置的BaseMapper中都已得到了实现,我们可以直接使用,接口如下:
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述

3.2 基于BaseMapper的测试

 	//插入
    @Test
    public void testInsert(){
	// INSERT INTO user  ( id, name, age, email )  VALUES  ( ?, ?, ?, ? )
        User user = new User(6,"张三",23,"zhangsan@126.com");

        int result = userMapper.insert(user);

        System.out.println("result="+result);

    }

    //删除
    @Test
    public void testDelete(){
     	 //根据Id删除用户
       	//DELETE FROM user WHERE id=?
      	int result = userMapper.deleteById(2L);

        //根据map集合删除
        //DELETE FROM user WHERE name = ? AND age = ?
        Map<String,Object> map = new HashMap<>();
        map.put("name","张三");
        map.put("age",23);
        int result = userMapper.deleteByMap(map);

        // 根据id批量删除
		// DELETE FROM user WHERE id IN ( ? , ? , ? )
        List<Integer> list = Arrays.asList(1, 2, 3);

        int result = userMapper.deleteBatchIds(list);
        System.out.println("result="+result);
    }

    //修改
    @Test
    public void testUpdate(){
//        UPDATE user SET name=?, email=? WHERE id=?
        User user = new User();
        user.setId(4L);
        user.setName("李四");
        user.setEmail("lisi@atguigu.com");
        int result = userMapper.updateById(user);
        System.out.println("result="+result);
    }

    //查询
    @Test
    public void testSelect(){
        //根据Id查询用户
//        SELECT id,name,age,email FROM user WHERE id=?
	 	User user = userMapper.selectById(5L);
	 	System.out.println(user);

//        SELECT id,name,age,email FROM user WHERE id IN ( ? , ? , ? )
		List<Integer> list = Arrays.asList(1, 2, 4);
		List<User> users = userMapper.selectBatchIds(list);
		users.forEach(System.out::println);

        Map<String,Object> map = new HashMap<>();
        map.put("age",23);
        List<User> users = userMapper.selectByMap(map);
        users.forEach(System.out::println);

    }

3.3 通用service

说明:

  1. 通用 Service CRUD 封装IService接口,进一步封装 CRUD 采用 get 查询单行remove 删除list 查询集合page 分页; 前缀命名方式区分 Mapper 层避免混淆,泛型 T 为任意实体对象。
  2. 建议如果存在自定义通用 Service 方法的可能,请创建自己的 IBaseService 继承Mybatis-Plus 提供的基类。
  3. 官网地址:https://baomidou.com/pages/49cc81/#service-crud-%E6%8E%A5%E5%8F%A3

3.3.1 IService

MyBatis-Plus中有一个接口 IService和其实现类 ServiceImpl,封装了常见的业务层逻辑详情查看源码IService和ServiceImpl。
在这里插入图片描述

3.3.2 创建service接口及实现类

UserServiceImpl

@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {

}

ServiceImpl<M,T>泛型是mapper和实体类。当我们对于继承的userservice中方法无法满足业务需求的时候,我们可以让类继承serviceimpl这个类。

UserService

public interface UserService  extends IService<User> {

}

注意:

  1. UserService继承IService模板提供的基础功能
  2. ServiceImpl实现了IService,提供了IService中基础功能的实现 ;若ServiceImpl无法满足业务需求,则可以使用自定的UserService定义方法,并在实现类中实现

3.3.3 在spring配置文件中设置自动扫描service的包

<!--设置自动扫描service的包-->
    <context:component-scan base-package="com.atguigu.mybatisplus.service"/>

3.3.4 测试(查询总记录数和批量添加)

//测试service接口
    @Autowired
    private UserService userService;

    //总记录数
    @Test
    public void testGetCount(){
        long count = userService.count();
        System.out.println("总记录数:"+count);
    }

    //批量添加
    //单个Insert语句循环i次完成批量添加
    @Test
    public void testAllInsert(){
        List<User> list = new ArrayList<>();
        for (int i = 0; i < 100 ; i++) {
            User user = new User();
            user.setName("abc"+i);
            user.setAge(20+i);
            list.add(user);
        }
        boolean b = userService.saveBatch(list);
        System.out.println("b:"+b);
    }

错误:

Duplicate entry ‘0’ for key ‘PRIMARY’
原因:发现了是数据库表设计不合理导致的;
因为主键设置不能为空,因此默认是以"0"来进行填充的。因此在数据插入时数据的主键id值被0占据,但由于之前已经有数据了,id为“0”的索引已经被占,在使用就会报这个错误,因此我们只需要对表中的主键“id”设置成自增即可。

纠正:为什么会出现这个问题,是因为在创建实体类的时候id属性的类型写成long了,应该写成Long,不然雪花算法是不会实现的。
大小写要注意啊。

4 常用注解

4.1 @TableName(类名与表名)

经过以上的测试,在使用MyBatis-Plus实现基本的CRUD时,我们并没有指定要操作的表,只是在Mapper接口继承BaseMapper时,设置了泛型User,而操作的表为user表。
由此得出结论,MyBatis-Plus在确定操作的表时,由BaseMapper的泛型决定,即实体类型决定,且默认操作的表名和实体类型的类名一致。

4.1.1 问题引出

若实体类类型的类名和要操作的表的表名不一致,会出现什么问题?
我们将表user更名为t_user,测试查询功能程序抛出异常,Table ‘mybatis_plus.user’ doesn’t exist,因为现在的表名为t_user,而默认操作的表名和实体类型的类名一致,即user表。
在这里插入图片描述

4.1.2 通过@TableName解决问题

在实体类类型上添加@TableName(“t_user”),标识实体类对应的表,即可成功执行SQL语句。
在这里插入图片描述

4.1.3 通过GlobalConfig解决问题

在开发的过程中,我们经常遇到以上的问题,即实体类所对应的表都有固定的前缀,例如t_或tbl_,此时,可以使用MyBatis-Plus提供的全局配置,为实体类所对应的表名设置默认的前缀,那么就不需要在每个实体类上通过@TableName标识实体类对应的表。
在spring-persist.xml中的sqlsessionfactorybean处进行修改。

 <!--使用mybatisplus-->
    <bean id="mybatisSqlSessionFactoryBean" class="com.baomidou.mybatisplus.extension.spring.MybatisSqlSessionFactoryBean">
        <!--指定mybatis配置文件-->
        <property name="configLocation" value="classpath:mybatis-config.xml"/>
        <!--指定mapper.xml-->
        <property name="mapperLocations" value="classpath:mappers/*Mapper.xml"/>
        <!--装配数据源-->
        <property name="dataSource" ref="dataSource"/>

        <!--设置mybatisplus的全局配置,即表的前缀-->
        <property name="globalConfig" ref="globalConfig"></property>
    </bean>



    <bean id="globalConfig" class="com.baomidou.mybatisplus.core.config.GlobalConfig">
        <property name="dbConfig">
            <bean id="config" class="com.baomidou.mybatisplus.core.config.GlobalConfig$DbConfig">
                <!--设置实体类所对应的表的前缀-->
                <property name="tablePrefix" value="t_"></property>
             </bean>
        </property>
    </bean>

4.2 @TableId(主键属性与表中字段)

经过以上的测试,MyBatis-Plus在实现CRUD时,会默认将id作为主键列,并在插入数据时,默认基于雪花算法的策略生成id。

4.2.1 问题引出

若实体类和表中表示主键的不是id,而是其他字段,例如uid,MyBatis-Plus会自动识别uid为主键列吗?
我们实体类中的属性id改为uid,将表中的字段id也改为uid,测试添加功能程序抛出异常,Field ‘uid’ doesn’t have a default value,说明MyBatis-Plus没有将uid作为主键赋值。
在这里插入图片描述

4.2.2 通过@TableId解决问题

在实体类中uid属性上通过@TableId将其标识为主键,即可成功执行SQL语句。

//将这个uid这个属性所对应的字段作为主键(实体类和数据库表中都是uid时,可以不写value)
    //value属性用于指定主键的字段(实体类中字段是id,表中字段是uid时,设置value来指定主键字段)
    //type属性设置主键生成策略,默认是雪花算法(ASSIGN_ID),主键递增(AUTO)
   @TableId(value="uid",type = IdType.AUTO)
    private long id;

4.2.3 @TableId的value属性

若实体类中主键对应的属性为id,而表中表示主键的字段为uid,此时若只在属性id上添加注解@TableId,则抛出异常Unknown column ‘id’ in ‘field list’,即MyBatis-Plus仍然会将id作为表的主键操作,而表中表示主键的是字段uid。
此时需要通过@TableId注解的value属性,指定表中的主键字段,
@TableId(“uid”)或@TableId(value=“uid”)
在这里插入图片描述

4.2.4 @TableId的type属性

type属性用来定义主键策略。
在这里插入图片描述

[1] 配置全局主键策略:

在spring-persist.xml中修改。

<bean id="globalConfig" class="com.baomidou.mybatisplus.core.config.GlobalConfig">
        <property name="dbConfig">
            <bean id="config" class="com.baomidou.mybatisplus.core.config.GlobalConfig$DbConfig">
                <!--设置实体类所对应的表的前缀-->
                <property name="tablePrefix" value="t_"></property>
                <!--设置全局主键策略-->
                <property name="idType" value="AUTO"></property>
             </bean>
        </property>
    </bean>

4.2.5 雪花算法

在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述

4.3 @TableField(普通属性与表中字段)

经过以上的测试,我们可以发现,MyBatis-Plus在执行SQL语句时,要保证实体类中的属性名和表中的字段名一致;
如果实体类中的属性名和字段名不一致的情况,会出现什么问题呢?

4.3.1 情况1

若实体类中的属性使用的是驼峰命名风格,而表中的字段使用的是下划线命名风格。
例如实体类属性userName,表中字段user_name。
此时MyBatis-Plus会自动将下划线命名风格转化为驼峰命名风格。
相当于在MyBatis中配置。

4.3.2 情况2

若实体类中的属性和表中的字段不满足情况1。
例如实体类属性name,表中字段username。
此时需要在实体类属性上使用@TableField(“username”)设置属性所对应的字段名。

//注意:如果实体类中属性名为:name,表中字段名也要为:name
   // 在不加@TableField注解的情况下,表中字段为:user_name 代码会报错。
   //指定属性对应的字段名
    //当实体类中是name,表中所对应的字段名是:user_name,可以使用该注解来实现指定属性对应的字段名
    @TableField("user_name")
     private String name;

4.4 @TableLogic(逻辑删除)

4.4.1 逻辑删除

逻辑删除

  • 物理删除:真实删除,将对应数据从数据库中删除,之后查询不到此条被删除的数据
  • 逻辑删除:假删除,将对应数据中代表是否被删除字段的状态修改为“被删除状态”,之后在数据库中仍旧能看到此条数据记录
  • 使用场景:可以进行数据恢复

4.4.2 实现逻辑删除

[1] 数据库中创建逻辑删除状态列,设置默认值为0

在这里插入图片描述

[2] 实体类中添加逻辑删除属性

//逻辑删除
    @TableLogic
    private Integer isDeleted;

[3] 测试

  • 测试删除功能,真正执行的是修改
    UPDATE t_user SET is_deleted=1 WHERE id=? AND is_deleted=0
  • 测试查询功能,被逻辑删除的数据默认不会被查询
    SELECT id,username AS name,age,email,is_deleted FROM t_user WHERE is_deleted=0

5 条件构造器和常用接口

5.1 wapper介绍

在这里插入图片描述
在这里插入图片描述

5.2 QueryWrapper

5.2.1 组装查询条件

    @Test
    public void test01(){
        //查询用户名包含王,年龄在80到90之间,邮箱名不为空的用户信息
        // SELECT uid AS id,user_name AS name,age,email,is_deleted FROM t_user WHERE is_deleted=0 AND (user_name LIKE ? AND age BETWEEN ? AND ? AND email IS NOT NULL)
      QueryWrapper<User> queryWrapper = new QueryWrapper<User>();
      queryWrapper.like("user_name","王")
              .between("age","80","90")
              .isNotNull("email");
        List<User> list = userMapper.selectList(queryWrapper);
        list.forEach(System.out::println);

    }

在这里插入图片描述

5.2.2 组装排序条件

 @Test
    public void test02(){
        //查询用户信息,按照年龄的降序排序,若年龄相同,则按照Id升序排序。(mysql中默认是升序排序)
        //SELECT uid AS id,user_name AS name,age,email,is_deleted FROM t_user WHERE is_deleted=0 ORDER BY age DESC,uid ASC
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.orderByDesc("age").orderByAsc("uid");
        List<User> list = userMapper.selectList(queryWrapper);
        list.forEach(System.out::println);
    }

在这里插入图片描述

5.2.3 组装删除条件

@Test
    public void test03(){
        //删除邮箱为null的用户
        //UPDATE t_user SET is_deleted=1 WHERE is_deleted=0 AND (email IS NULL)
        //出现这个是因为我们设置了逻辑删除,即删除变成了修改,将状态从0(未删除状态)--->1(已删除状态);
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.isNull("email");
        int result = userMapper.delete(queryWrapper);
        System.out.println(result);
    }

5.2.4 条件的优先级

	/**
     * update(User entity,Wrapper<User> updateWrapper)
     * 第一个参数为修改的内容,第二个参数为设置修改的条件
     参数1设置修改的字段和值,参数2是查询符合的条件
     **/

    @Test
    public void test04(){
        //条件包装器中条件之间默认是and连接。我们不需要手动设置,但是如果是或,我们需要手动设置or.
        //将(年龄大于80并且用户名中包含有王)或邮箱为null的用户信息修改
        //UPDATE t_user SET user_name=?, email=? WHERE is_deleted=0 AND (age > ? AND user_name LIKE ? OR email IS NULL)
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        //gt  大于   like 模糊查询
        queryWrapper.gt("age",80)
                .like("user_name","王")
                .or()
                .isNull("email");
        User user = new User();
        user.setName("测试修改1");
        user.setEmail("test@atguigu.com");
        int result = userMapper.update(user, queryWrapper);
        System.out.println("result:"+ result);

    }

@Test
    public void test05(){
        //将用户名中包含王并且(年龄大于80或邮箱为null)的用户信息修改
        //当条件构造器中有and和or时,lambda中的条件优先执行
       // UPDATE t_user SET user_name=?, email=? WHERE is_deleted=0 AND (user_name LIKE ? AND (age > ? AND email IS NULL))
       //i 指的是条件构造器 
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.like("user_name","王")
                .and(i -> i.gt("age",80).isNull("email"));
        User user  = new User();
        user.setName("小红");
        user.setEmail("test@atguigu.com");
        int result = userMapper.update(user, queryWrapper);
        System.out.println("result:"+result);

    }

5.2.5 组装select子句

	@Test
    public void test06(){
        //查询用户的用户名,年龄,邮箱信息
        //SELECT user_name,age,email FROM t_user WHERE is_deleted=0
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.select("user_name","age","email");
        List<Map<String, Object>> maps = userMapper.selectMaps(queryWrapper);
        maps.forEach(System.out::println);
    }

在这里插入图片描述

5.2.6 实现子查询

  @Test
    public void test07(){
        //查询id小于等于3的用户信息
        //SELECT uid AS id,user_name AS name,age,email,is_deleted FROM t_user WHERE is_deleted=0 AND (uid IN (select uid from t_user where uid <= 3))
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.inSql("uid","select uid from t_user where uid <= 3");
        List<User> list = userMapper.selectList(queryWrapper);
        list.forEach(System.out::println);
    }

在这里插入图片描述

5.3 UpdataWrapper

//**************** updatewrapper ****************//

    @Test
    public void test08(){
        //将用户名中包含王并且(年龄大于80或邮箱为null)的用户信息修改
        //UPDATE t_user SET user_name=?,email=? WHERE is_deleted=0 AND (user_name LIKE ? AND (age > ? OR email IS NULL))
        //lambda 中消费者接口模型
        //updatewrapper可以直接设置查询条件和填充值。
        UpdateWrapper<User> updateWrapper = new UpdateWrapper<>();
        updateWrapper.like("user_name","王")
                .and(i -> i.gt("age","80").or().isNull("email"));
        updateWrapper.set("user_name","小黑").set("email","abc@atguigu.com");
        userMapper.update(null,updateWrapper);
    }

5.4 condition

在真正开发的过程中,组装条件是常见的功能,而这些条件数据来源于用户输入,是可选的,因此我们在组装这些条件时,必须先判断用户是否选择了这些条件,若选择则需要组装该条件,若没有选择则一定不能组装,以免影响SQL执行的结果。
方案1:

 @Test
    public void test09(){
        //接收到的浏览器的数据传输到服务器中
        String username= "";
        Integer ageBegin = 20;
        Integer ageEnd = 30;
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        //SELECT uid AS id,user_name AS name,age,email,is_deleted FROM t_user WHERE is_deleted=0 AND (age >= ? AND age <= ?)
        if(StringUtils.isNotBlank(username)){
            //isnotblank判断某个字符不为空字符串,不为null,不为空白符
            queryWrapper.like("user_name",username);
        }
        if(ageBegin != null){
            queryWrapper.ge("age",ageBegin);
        }
        if(ageEnd != null){
            queryWrapper.le("age",ageEnd);
        }
        List<User> list = userMapper.selectList(queryWrapper);
        list.forEach(System.out::println);
    }

上面的实现方案没有问题,但是代码比较复杂,我们可以使用带condition参数的重载方法构建查询条件,简化代码的编写.

方案2:使用condition

    @Test
    public void test10(){
        //接收到的浏览器的数据传输到服务器中
        //SELECT uid AS id,user_name AS name,age,email,is_deleted FROM t_user WHERE is_deleted=0 AND (age >= ? AND age <= ?)
        String username= "";
        Integer ageBegin = 20;
        Integer ageEnd = 30;
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.like(StringUtils.isNotBlank(username),"user_name",username)
                .ge(ageBegin != null,"age",ageBegin)
                .le(ageEnd != null,"age",ageEnd);

        List<User> list = userMapper.selectList(queryWrapper);
        list.forEach(System.out::println);

    }

5.5 LambdaQueryWrapper

 @Test
    public void test11(){
        //接收到的浏览器的数据传输到服务器中
        //SELECT uid AS id,user_name AS name,age,email,is_deleted FROM t_user WHERE is_deleted=0 AND (age >= ? AND age <= ?)
        //LambdaQueryWrapper防止字段名写错,可以使用函数式接口(User::getAge),来访问实体类中的某一个属性所对应的字段名。自动将其作为我们的条件。
        String username= "";
        Integer ageBegin = 20;
        Integer ageEnd = 30;
        LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.like(StringUtils.isNotBlank(username),User::getName,username)
                .ge(ageBegin != null,User::getAge,ageBegin)
                .le(ageEnd != null,User::getAge,ageEnd);

        List<User> list = userMapper.selectList(queryWrapper);
        list.forEach(System.out::println);

    }

5.6 LambdaUpdateWrapper

 @Test
    public void test12(){
        //将用户名中包含王并且(年龄大于80或邮箱为null)的用户信息修改
        //UPDATE t_user SET user_name=?,email=? WHERE is_deleted=0 AND (user_name LIKE ? AND (age > ? OR email IS NULL))
        //lambda 中消费者接口模型
        //updatewrapper可以直接设置查询条件和设置修改的字段并设置值。不需要设置实体类。
        LambdaUpdateWrapper<User> updateWrapper = new LambdaUpdateWrapper<>();
        updateWrapper.like(User::getName,"王")
                .and(i -> i.gt(User::getAge,"80").or().isNull(User::getEmail));
        updateWrapper.set(User::getName,"小黑").set(User::getEmail,"abc@atguigu.com");
        userMapper.update(null,updateWrapper);
    }

6 插件

6.1 分页插件

6.1.1 添加配置

 <!--使用mybatisplus-->
    <bean id="mybatisSqlSessionFactoryBean" class="com.baomidou.mybatisplus.extension.spring.MybatisSqlSessionFactoryBean">
        <!--指定mybatis配置文件-->
        <property name="configLocation" value="classpath:mybatis-config.xml"/>
        <!--指定mapper.xml-->
        <property name="mapperLocations" value="classpath:mappers/*Mapper.xml"/>
        <!--装配数据源-->
        <property name="dataSource" ref="dataSource"/>
        <!--设置mybatisplus的全局配置,即表的前缀-->
        <property name="globalConfig" ref="globalConfig"></property>
        <!--配置插件-->
        <property name="plugins">
            <array>
                <ref bean="mybatisPlusInterceptor"></ref>
            </array>
        </property>
    </bean>

    <!--配置MyBatis-Plus插件-->
    <bean id="mybatisPlusInterceptor" class="com.baomidou.mybatisplus.extension.plugins.MybatisPlusInterceptor">
        <property name="interceptors">
            <list>
                <ref bean="paginationInnerInterceptor"></ref>
            </list>
        </property>
    </bean>


    <!--配置Mybatis-plus分页插件的bean-->
    <bean id="paginationInnerInterceptor" class="com.baomidou.mybatisplus.extension.plugins.inner.PaginationInnerInterceptor">
        <!--设置数据库类型-->
        <property name="dbType" value="MYSQL"></property>
    </bean>

6.1.2 测试

@SpringJUnitConfig(locations = {"classpath:spring-persist.xml"})
public class MyBatisPlusPageTest {
    @Autowired
    private UserMapper userMapper;

    @Test
    public void testPage(){
        //设置分页参数(参数1:当前页数,参数2:每页显示记录条数)
        Page<User> page = new Page<>(1,4);
        userMapper.selectPage(page,null);
        //获取分页数据
        List<User> list = page.getRecords();
        list.forEach(System.out::println);
        System.out.println("当前页:"+page.getCurrent());
        System.out.println("每页显示的条数:"+page.getSize());
        System.out.println("总记录数:"+page.getTotal());
        System.out.println("是否有上一页:"+page.hasPrevious());
        System.out.println("是否有下一页:"+page.hasNext());

    }

}

在这里插入图片描述

6.2 xml自定义分页

6.2.1 UserMapper中定义接口方法


public interface UserMapper extends BaseMapper<User> {

    /**
     * 通过年龄查询用户信息并分页
     * @param page mybatis-plus所提供的分页对象,必须位于第一个参数的位置
     * @param age
     * @return
     */
    //如果我们想要使用分页插件在我们自定义的查询语句上,参数返回值必须是Page,第一个参数也必须是Page..
    Page<User> selectPageVo(@Param("page") Page<User> page,@Param("age") Integer age);


}

6.2.2 UserMapper.xml中编写SQL

<!--    Page<User> selectPageVo(@Param("page") Page<User> page,@Param("age") Integer age);-->
        <select id="selectPageVo" resultType="user">
            select uid,user_name,age,email from t_user where age > #{age}
        </select>

6.2.3 测试

  //测试xml自定义分页

    @Test
    public void testPageVo(){
        Page<User> page = new Page<>(1,3);
        userMapper.selectPageVo(page,20);
        System.out.println("当前页:"+page.getCurrent());
        System.out.println("每页显示的条数:"+page.getSize());
        System.out.println("总记录数:"+page.getTotal());
        System.out.println("是否有上一页:"+page.hasPrevious());
        System.out.println("是否有下一页:"+page.hasNext());

    }

6.3 乐观锁

6.3.1 场景

一件商品,成本价是80元,售价是100元。老板先是通知小李,说你去把商品价格增加50元。小李正在玩游戏,耽搁了一个小时。正好一个小时后,老板觉得商品价格增加到150元,价格太高,可能会影响销量。又通知小王,你把商品价格降低30元。
此时,小李和小王同时操作商品后台系统。小李操作的时候,系统先取出商品价格100元;小王也在操作,取出的商品价格也是100元。小李将价格加了50元,并将100+50=150元存入了数据库;小王将商品减了30元,并将100-30=70元存入了数据库。是的,如果没有锁,小李的操作就完全被小王的覆盖了。
现在商品价格是70元,比成本价低10元。几分钟后,这个商品很快出售了1千多件商品,老板亏1万多。

6.3.2 乐观锁与悲观锁

上面的故事,如果是乐观锁,小王保存价格前,会检查下价格是否被人修改过了。如果被修改过了,则重新取出的被修改后的价格,150元,这样他会将120元存入数据库。
如果是悲观锁,小李取出数据后,小王只能等小李操作完之后,才能对价格进行操作,也会保证最终的价格是120元。

6.3.3 模拟修改冲突

[1] 数据库中增加商品表

CREATE TABLE t_product
(
id BIGINT(20) NOT NULL COMMENT '主键ID',
NAME VARCHAR(30) NULL DEFAULT NULL COMMENT '商品名称',
price INT(11) DEFAULT 0 COMMENT '价格',
VERSION INT(11) DEFAULT 0 COMMENT '乐观锁版本号',
PRIMARY KEY (id)
);

[2] 添加数据

INSERT INTO t_product (id, NAME, price) VALUES (1, '外星人笔记本', 100);

[3] 创建product实体类

@Data
public class Product {
    private long id;
    private String name;
    private Integer price;
    private Integer version;
}

[4] 创建ProductMapper

public interface ProductMapper extends BaseMapper<Product> {
}

[5] 测试

@Test
    public void test01(){
        //小李查询商品价格
        Product productli = productMapper.selectById(1);
        System.out.println("小李查询的商品价格:"+productli.getPrice());
        //小王查询商品价格
        Product productwang = productMapper.selectById(1);
        System.out.println("小王查询的商品价格:"+productwang.getPrice());
        //小李将价格+50
        productli.setPrice(productli.getPrice() + 50);
        productMapper.updateById(productli);
        //小王将价格-30
        productwang.setPrice(productwang.getPrice() - 30);
        productMapper.updateById(productwang);
        //老板查询价格
        Product productlaoban = productMapper.selectById(1);
        System.out.println("老板查询的商品价格:"+productlaoban.getPrice());
    }

6.3.4 乐观锁实现流程

  • 数据库中添加version字段
  • 取出记录时,获取当前version

SELECT id,name,price,version FROM product WHERE id=1

更新时,version + 1,如果where语句中的version版本不对,则更新失败

UPDATE product SET price=price+50, version=version + 1 WHERE id=1 AND
version=1

6.3.5 Mybatis-Plus实现乐观锁

[1] 修改实体类

@Data
public class Product {
    private long id;
    private String name;
    private Integer price;
    @Version  //表示乐观锁版本号字段
    private Integer version;
}

[2] 添加乐观锁插件配置

 <!--配置MyBatis-Plus插件-->
    <bean id="mybatisPlusInterceptor" class="com.baomidou.mybatisplus.extension.plugins.MybatisPlusInterceptor">
        <property name="interceptors">
            <list>
                <ref bean="paginationInnerInterceptor"></ref>

                <ref bean="optimisticLockerInnerInterceptor"></ref>
            </list>
        </property>
    </bean>

 <!--配置乐观锁插件-->
    <bean id="optimisticLockerInnerInterceptor" class="com.baomidou.mybatisplus.extension.plugins.inner.OptimisticLockerInnerInterceptor">
    </bean>

[3] 测试修改冲突

小李查询商品信息:
SELECT id,name,price,version FROM t_product WHERE id=?
小王查询商品信息:
SELECT id,name,price,version FROM t_product WHERE id=?
小李修改商品价格,自动将version+1
UPDATE t_product SET name=?, price=?, version=? WHERE id=? AND version=?
Parameters: 外星人笔记本(String), 150(Integer), 1(Integer), 1(Long), 0(Integer)
小王修改商品价格,此时version已更新,条件不成立,修改失败
UPDATE t_product SET name=?, price=?, version=? WHERE id=? AND version=?
Parameters: 外星人笔记本(String), 70(Integer), 1(Integer), 1(Long), 0(Integer)
最终,小王修改失败,查询价格:150
SELECT id,name,price,version FROM t_product WHERE id=?

[4] 优化流程

@Test
    public void test01(){
        //小李查询商品价格
        Product productli = productMapper.selectById(1);
        System.out.println("小李查询的商品价格:"+productli.getPrice());
        //小王查询商品价格
        Product productwang = productMapper.selectById(1);
        System.out.println("小王查询的商品价格:"+productwang.getPrice());
        //小李将价格+50
        productli.setPrice(productli.getPrice() + 50);
        productMapper.updateById(productli);
        //小王将价格-30
        productwang.setPrice(productwang.getPrice() - 30);
        int result = productMapper.updateById(productwang);
        if(result == 0){
            //操作失败,重新尝试
            Product productNew = productMapper.selectById(1);
            productNew.setPrice(productNew.getPrice() - 30);
            productMapper.updateById(productNew);
        }
        //老板查询价格
        Product productlaoban = productMapper.selectById(1);
        System.out.println("老板查询的商品价格:"+productlaoban.getPrice());
    }

7 通用枚举

通用枚举表中的有些字段值是固定的,例如性别(男或女),此时我们可以使用MyBatis-Plus的通用枚举来实现。

7.1 数据库表添加字段sex

在这里插入图片描述

7.2 创建通用枚举类型

@Getter
public enum SexEnum {
    MALE(1,"男"),
    FEMALE(2,"女");

    @EnumValue //将注解标识的属性加入到数据库中
    private Integer sex;
    private String sexName;

    SexEnum(Integer sex, String sexName) {
        this.sex = sex;
        this.sexName = sexName;
    }
}

7.3 配置扫描通用枚举

配置扫描通用枚举

 <!--使用mybatisplus-->
    <bean id="mybatisSqlSessionFactoryBean" class="com.baomidou.mybatisplus.extension.spring.MybatisSqlSessionFactoryBean">
        <!--指定mybatis配置文件-->
        <property name="configLocation" value="classpath:mybatis-config.xml"/>
        <!--指定mapper.xml-->
        <property name="mapperLocations" value="classpath:mappers/*Mapper.xml"/>
        <!--装配数据源-->
        <property name="dataSource" ref="dataSource"/>
        <!--设置mybatisplus的全局配置,即表的前缀-->
        <property name="globalConfig" ref="globalConfig"></property>
        <!--配置扫描通用枚举-->
        <property name="typeEnumsPackage" value="com.atguigu.mybatisplus.enums"></property>
        <!--配置插件-->
        <property name="plugins">
            <array>
                <ref bean="mybatisPlusInterceptor"></ref>
            </array>
        </property>
    </bean>

7.4 测试

  //测试Enum

    @Test
    public void testEnum(){
        User user = new User();
        user.setName("admin");
        user.setAge(33);
        user.setSex(SexEnum.MALE);
        int result = userMapper.insert(user);
        System.out.println(result);
    }

8 代码生成器

8.1 引入依赖

<!--代码生成器逆向工程依赖-->
        <dependency>
            <groupId>com.baomidou</groupId>
            <artifactId>mybatis-plus-generator</artifactId>
            <version>3.5.1</version>
        </dependency>
        <!--代码生成器中 freemarker引擎模板需要这个依赖-->
        <dependency>
            <groupId>org.freemarker</groupId>
            <artifactId>freemarker</artifactId>
            <version>2.3.31</version>
        </dependency>

8.2 快速生成

创建一个类:FastAutoGeneratorTest

public class FastAutoGeneratorTest {
    public static void main(String[] args) {
        FastAutoGenerator.create("jdbc:mysql://127.0.0.1:13306/mybatis_plus",
                "root", "abc123")
                .globalConfig(builder -> {
                    builder.author("atguigu") // 设置作者
//.enableSwagger() // 开启 swagger 模式
                            .fileOverride() // 覆盖已生成文件
                            .outputDir("E://javacode//mybatis_plus"); // 指定输出目录
                })
                .packageConfig(builder -> {
                    builder.parent("com.atguigu") // 设置父包名
                            .moduleName("mybatisplus") // 设置父包模块名
                            .pathInfo(Collections.singletonMap(OutputFile.mapperXml, "E://javacode//mybatis_plus"));
// 设置mapperXml生成路径
                })
                .strategyConfig(builder -> {
                    builder.addInclude("t_user") // 设置需要生成的表名
                            .addTablePrefix("t_", "c_"); // 设置过滤表前缀
                })
                .templateEngine(new FreemarkerTemplateEngine()) // 使用Freemarker引擎模板,默认的是Velocity引擎模板
                .execute();
    }
}

9 MyBatisX插件

MyBatis-Plus为我们提供了强大的mapper和service模板,能够大大的提高开发效率
但是在真正开发过程中,MyBatis-Plus并不能为我们解决所有问题,例如一些复杂的SQL,多表联查,我们就需要自己去编写代码和SQL语句,我们该如何快速的解决这个问题呢,这个时候可以使用MyBatisX插件。
MyBatisX一款基于 IDEA 的快速开发插件,为效率而生。

MyBatisX插件用法:https://baomidou.com/pages/ba5b24/

9.1 安装插件

安装方法:打开 IDEA,进入 File -> Settings -> Plugins -> Browse Repositories,输入 mybatisx 搜索并安装

9.2 功能

9.2.1 XML跳转

当mapper映射文件和mapper很多的时候,可以快速定位并跳转到对应的类容上。

9.2.2 快速生成代码

[1]首先需要在datasource中进行配置

  1. 连接mysql
    在这里插入图片描述

  2. 选择驱动
    在这里插入图片描述

  3. 可以直接选择旧版本的驱动。或者按提示下载
    在这里插入图片描述

  4. 登录后选择数据库、表,然后点击右键选择mybatisx.
    在这里插入图片描述

  5. 表的基本配置
    在这里插入图片描述

  6. 生成的基本配置
    在这里插入图片描述

  7. 选择好后会自动帮我们生成各种组件
    在这里插入图片描述

  8. 如果我们要自定义查询功能,我们只需要在mapper中写我们的方法名,插件会自动帮助我们补全方法名并且快速生成相对应的sql语句放在mapper映射文件中。

在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
此处报错是因为本案例最开始使用的存放mapper映射文件的目录名是mappers。实际应该是mapper


总结

mybatsi-plus可以快速帮助我们完成spring和mybatsi的整合及搭建功能。

posted @ 2022-10-26 18:01  hxld  阅读(75)  评论(0编辑  收藏  举报