1. 官方网址

https://baomidou.com/

2. 基本应用

2.1 Mybatis + MP

2.1.1 导入依赖

  1. <dependencies>
  2. <!-- mybatis-plus插件依赖 -->
  3. <dependency>
  4. <groupId>com.baomidou</groupId>
  5. <artifactId>mybatis-plus</artifactId>
  6. <version>3.1.1</version>
  7. </dependency>
  8. <!--Mysql-->
  9. <dependency>
  10. <groupId>mysql</groupId>
  11. <artifactId>mysql-connector-java</artifactId>
  12. <version>5.1.47</version>
  13. </dependency>
  14. <!--连接池-->
  15. <dependency>
  16. <groupId>com.alibaba</groupId>
  17. <artifactId>druid</artifactId>
  18. <version>1.0.11</version>
  19. </dependency>
  20. <!--简化bean代码的⼯具包-->
  21. <dependency>
  22. <groupId>org.projectlombok</groupId>
  23. <artifactId>lombok</artifactId>
  24. <version>1.18.4</version>
  25. </dependency>
  26. <dependency>
  27. <groupId>junit</groupId>
  28. <artifactId>junit</artifactId>
  29. <version>4.12</version>
  30. </dependency>
  31. <dependency>
  32. <groupId>org.slf4j</groupId>
  33. <artifactId>slf4j-log4j12</artifactId>
  34. <version>1.6.4</version>
  35. </dependency>
  36. </dependencies>

2.1.2 先配置纯Mybatis应用

  1. jdbc.properties:

    1. jdbc.driver=com.mysql.jdbc.Driver
    2. jdbc.url=jdbc:mysql://localhost:3306/atm?characterEncoding=utf-8
    3. jdbc.username=root
    4. jdbc.password=root
  2. 编写Mybatis主配置文件mybatis-config.xml

    1. <?xml version="1.0" encoding="UTF-8" ?>
    2. <!DOCTYPE configuration
    3. PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
    4. "http://mybatis.org/dtd/mybatis-3-config.dtd">
    5. <configuration>
    6. <properties resource="jdbc.properties"></properties>
    7. <!--environments: 运⾏环境-->
    8. <environments default="development">
    9. <environment id="development">
    10. <!--当前的事务事务管理器是JDBC-->
    11. <transactionManager type="JDBC"></transactionManager>
    12. <!--数据源信息 POOLED:使⽤mybatis的连接池-->
    13. <dataSource type="POOLED">
    14. <property name="driver" value="${jdbc.driver}"/>
    15. <property name="url" value="${jdbc.url}"/>
    16. <property name="username" value="${jdbc.username}"/>
    17. <property name="password" value="${jdbc.password}"/>
    18. </dataSource>
    19. </environment>
    20. </environments>
    21. <!--引⼊映射配置⽂件-->
    22. <mappers>
    23. <mapper package="mapper"></mapper>
    24. </mappers>
    25. </configuration>
  3. 编写实体类User

    1. @Data // getter setter @toString
    2. @NoArgsConstructor // 无参构造
    3. @AllArgsConstructor // 全参构造
    4. public class User {
    5. private Long id;
    6. private String name;
    7. private Integer age;
    8. private String email;
    9. }
  4. 编写UserMapper接⼝

    1. public interface UserMapper {
    2. List<User> findAll();
    3. }
  5. 编写UserMapper.xml⽂件

    1. <?xml version="1.0" encoding="UTF-8" ?>
    2. <!DOCTYPE mapper
    3. PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
    4. "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
    5. <mapper namespace="com.lagou.mapper.UserMapper">
    6. <!-- 查询所有 -->
    7. <select id="findAll" resultType="com.lagou.pojo.User">
    8. select * from user
    9. </select>
    10. </mapper>
  6. 测试

    1. public class MPTest {
    2. @Test
    3. public void test1() throws IOException {
    4. InputStream resourceAsStream =
    5. Resources.getResourceAsStream("mybatis-config.xml");
    6. SqlSessionFactory sqlSessionFactory = new
    7. SqlSessionFactoryBuilder().build(resourceAsStream);
    8. SqlSession sqlSession = sqlSessionFactory.openSession();
    9. UserMapper mapper = sqlSession.getMapper(UserMapper.class);
    10. List<User> all = mapper.findAll();
    11. for (User user : all) {
    12. System.out.println(user);
    13. }
    14. }
    15. }

    2.1.3 然后配置无侵入使用MP(Mybatis + MP应用)

  7. 第⼀步,将UserMapper继承BaseMapper,将拥有了BaseMapper中的所有⽅法:

    1. import com.baomidou.mybatisplus.core.mapper.BaseMapper;
    2. import com.lagou.pojo.User;
    3. public interface UserMapper extends BaseMapper<User> {
    4. List<User> findAll();
    5. }
  8. 第⼆步,使⽤MP中的MybatisSqlSessionFactoryBuilder进程构建:

    1. @Test
    2. public void test2() throws IOException {
    3. InputStream resourceAsStream =
    4. Resources.getResourceAsStream("mybatis-config.xml");
    5. // 这⾥使⽤的是MP中的MybatisSqlSessionFactoryBuilder
    6. SqlSessionFactory sqlSessionFactory = new
    7. MybatisSqlSessionFactoryBuilder().build(resourceAsStream);
    8. SqlSession sqlSession = sqlSessionFactory.openSession();
    9. UserMapper mapper = sqlSession.getMapper(UserMapper.class);
    10. // 可以调⽤BaseMapper中定义的⽅法
    11. List<User> all = mapper.selectList(null);
    12. for (User user : all) {
    13. System.out.println(user);
    14. }
    15. // 也可以使用原生的Mybatis手写方法
    16. List<User> all2 = mapper.findAll();
    17. for (User user : all2) {
    18. System.out.println(user);
    19. }
    20. }

    2.2 Spring + Mybatis + MP

  9. 引入依赖 ```xml

    5.1.6.RELEASE

com.baomidou mybatis-plus 3.1.1 mysql mysql-connector-java 5.1.47 com.alibaba druid 1.0.11 org.projectlombok lombok 1.18.4 junit junit 4.12 org.slf4j slf4j-log4j12 1.6.4 org.springframework spring-webmvc ${spring.version} org.springframework spring-jdbc ${spring.version} org.springframework spring-test ${spring.version}

  1. 2. 编写jdbc.properties
  2. ```properties
  3. jdbc.driver=com.mysql.jdbc.Driver
  4. jdbc.url=jdbc:mysql://127.0.0.1:3306/mp?serverTimezone=GMT%2B8&useSSL=false
  5. jdbc.username=root
  6. jdbc.password=root
  1. 编写Spring主配置文件applicationContext.xml

    1. <?xml version="1.0" encoding="UTF-8"?>
    2. <beans xmlns="http://www.springframework.org/schema/beans"
    3. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    4. xmlns:context="http://www.springframework.org/schema/context"
    5. xsi:schemaLocation="
    6. http://www.springframework.org/schema/beans
    7. http://www.springframework.org/schema/beans/spring-beans.xsd
    8. http://www.springframework.org/schema/context
    9. http://www.springframework.org/schema/context/spring- context.xsd">
    10. <!--引⼊properties-->
    11. <context:property-placeholder location="classpath:jdbc.properties"/>
    12. <!--dataSource-->
    13. <bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource">
    14. <property name="driverClassName" value="${jdbc.driver}"/>
    15. <property name="url" value="${jdbc.url}"/>
    16. <property name="username" value="${jdbc.username}"/>
    17. <property name="password" value="${jdbc.password}"/>
    18. </bean>
    19. <!--这⾥使⽤MP提供的sqlSessionFactory,完成spring与mp的整合-->
    20. <bean id="sqlSessionFactory"
    21. class="com.baomidou.mybatisplus.extension.spring.MybatisSqlSessionFactoryBean"
    22. >
    23. <property name="dataSource" ref="dataSource"/>
    24. </bean>
    25. <!--扫描mapper接⼝,使⽤的依然是mybatis原⽣的扫描器-->
    26. <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
    27. <property name="basePackage" value="com.atm.mapper"/>
    28. </bean>
    29. </beans>
  2. 编写User对象以及UserMapper接⼝: ```java @Data @NoArgsConstructor @AllArgsConstructor public class User { private Long id; private String name; private Integer age; private String email; }

public interface UserMapper extends BaseMapper { List findAll(); }

  1. 5. 编写测试⽤例:
  2. ```java
  3. @RunWith(SpringJUnit4ClassRunner.class)
  4. @ContextConfiguration(locations = "classpath:applicationContext.xml")
  5. public class TestSpringMP {
  6. @Autowired
  7. private UserMapper userMapper;
  8. @Test
  9. public void test2() throws IOException {
  10. List<User> users = this.userMapper.selectList(null);
  11. for (User user : users) {
  12. System.out.println(user);
  13. }
  14. }
  15. }

2.3 SpringBoot + MP

  1. 导入依赖

    1. <dependencies>
    2. <dependency>
    3. <groupId>org.springframework.boot</groupId>
    4. <artifactId>spring-boot-starter</artifactId>
    5. <exclusions>
    6. <exclusion>
    7. <groupId>org.springframework.boot</groupId>
    8. <artifactId>spring-boot-starter-logging</artifactId>
    9. </exclusion>
    10. </exclusions>
    11. </dependency>
    12. <dependency>
    13. <groupId>org.springframework.boot</groupId>
    14. <artifactId>spring-boot-starter-test</artifactId>
    15. <scope>test</scope>
    16. </dependency>
    17. <!--简化代码的⼯具包-->
    18. <dependency>
    19. <groupId>org.projectlombok</groupId>
    20. <artifactId>lombok</artifactId>
    21. <optional>true</optional>
    22. </dependency>
    23. <!--mybatis-plus的springboot⽀持-->
    24. <dependency>
    25. <groupId>com.baomidou</groupId>
    26. <artifactId>mybatis-plus-boot-starter</artifactId>
    27. <version>3.1.1</version>
    28. </dependency>
    29. <!--mysql驱动-->
    30. <dependency>
    31. <groupId>mysql</groupId>
    32. <artifactId>mysql-connector-java</artifactId>
    33. <version>5.1.47</version>
    34. </dependency>
    35. <dependency>
    36. <groupId>org.slf4j</groupId>
    37. <artifactId>slf4j-log4j12</artifactId>
    38. </dependency>
    39. </dependencies>
    40. <build>
    41. <plugins>
    42. <plugin>
    43. <groupId>org.springframework.boot</groupId>
    44. <artifactId>spring-boot-maven-plugin</artifactId>
    45. </plugin>
    46. </plugins>
    47. </build>
  2. 编写application.properties

    1. spring.datasource.driver-class-name=com.mysql.jdbc.Driver
    2. spring.datasource.url=jdbc:mysql://127.0.0.1:3306/mp?
    3. useUnicode=true&characterEncoding=utf8&autoReconnect=true&allowMultiQueries=tr
    4. ue&useSSL=false
    5. spring.datasource.username=root
    6. spring.datasource.password=root
  3. 编写pojo

    1. @Data
    2. @NoArgsConstructor
    3. @AllArgsConstructor
    4. public class User {
    5. private Long id;
    6. private String name;
    7. private Integer age;
    8. private String email;
    9. }
  4. 编写mapper

    1. public interface UserMapper extends BaseMapper<User> {
    2. }
  5. 编写启动类

    1. package com.atm.mp;
    2. import org.mybatis.spring.annotation.MapperScan;
    3. import org.springframework.boot.SpringApplication;
    4. import org.springframework.boot.WebApplicationType;
    5. import org.springframework.boot.autoconfigure.SpringBootApplication;
    6. import org.springframework.boot.builder.SpringApplicationBuilder;
    7. @MapperScan("com.atm.mp.mapper") //设置mapper接⼝的扫描包
    8. @SpringBootApplication
    9. public class MyApplication {
    10. public static void main(String[] args) {
    11. SpringApplication.run(MyApplication.class, args);
    12. }
    13. }
  6. 编写测试⽤例

    1. @RunWith(SpringRunner.class)
    2. @SpringBootTest
    3. public class UserMapperTest {
    4. @Autowired
    5. private UserMapper userMapper;
    6. @Test
    7. public void testSelect() {
    8. List<User> userList = userMapper.selectList(null);
    9. for (User user : userList) {
    10. System.out.println(user);
    11. }
    12. }
    13. }

    3. 通用CRUD

    3.1 新增

    3.2 修改

    3.3 删除

    3.4 查询

  7. 普通查询

  8. 分页查询
    1. 方法定义: ```java /**
  • 根据 entity 条件,查询全部记录(并翻⻚) *
  • @param page 分⻚查询条件(可以为 RowBounds.DEFAULT)
  • @param queryWrapper 实体对象封装操作类(可以为 null) */ IPage selectPage(IPage page, @Param(Constants.WRAPPER) Wrapper queryWrapper);

    1. 2. 配置分⻚插件:
    2. ```java
    3. package com.atm.mp;
    4. import com.baomidou.mybatisplus.extension.plugins.PaginationInterceptor;
    5. import org.mybatis.spring.annotation.MapperScan;
    6. import org.springframework.context.annotation.Bean;
    7. import org.springframework.context.annotation.Configuration;
    8. @Configuration
    9. @MapperScan("com.atm.mapper") //设置mapper接⼝的扫描包
    10. public class MybatisPlusConfig {
    11. /**
    12. * 分⻚插件
    13. */
    14. @Bean
    15. public PaginationInterceptor paginationInterceptor() {
    16. return new PaginationInterceptor();
    17. }
    18. }
    1. 测试⽤例:
      1. @RunWith(SpringRunner.class)
      2. @SpringBootTest
      3. public class UserMapperTest {
      4. @Autowired
      5. private UserMapper userMapper;
      6. @Test
      7. public void testSelectPage() {
      8. QueryWrapper<User> wrapper = new QueryWrapper<User>();
      9. wrapper.gt("age", 20); //年龄⼤于20岁
      10. Page<User> page = new Page<>(1,1);
      11. //根据条件查询数据
      12. IPage<User> iPage = this.userMapper.selectPage(page, wrapper);
      13. System.out.println("数据总条数:" + iPage.getTotal());
      14. System.out.println("总⻚数:" + iPage.getPages());
      15. List<User> users = iPage.getRecords();
      16. for (User user : users) {
      17. System.out.println("user = " + user);
      18. }
      19. }
      20. }

      4. 配置

      4.1 基本配置

      4.1.1 配置文件configuration

      MyBatis 配置⽂件位置,如果有单独的 MyBatis 配置,请将其路径配置到 configLocation 中。
      springboot:
      1. mybatis-plus.config-location = classpath:mybatis-config.xml
      spring mvc:
      1. <bean id="sqlSessionFactory"
      2. class="com.baomidou.mybatisplus.extension.spring.MybatisSqlSessionFactoryBean"
      3. >
      4. <property name="configLocation" value="classpath:mybatis-config.xml"/>
      5. </bean>

      4.1.2 mapper路径mapperLocations

      MyBatis Mapper 所对应的 XML ⽂件位置,如果您在 Mapper 中有⾃定义⽅法(XML 中有⾃定义实
      现),需要进⾏该配置,告诉 Mapper 所对应的 XML ⽂件位置。
      springboot:
      1. mybatis-plus.mapper-locations = classpath*:mybatis/*.xml
      spring mvc:
      1. <bean id="sqlSessionFactory"
      2. class="com.baomidou.mybatisplus.extension.spring.MybatisSqlSessionFactoryBean"
      3. >
      4. <property name="mapperLocations" value="classpath*:mybatis/*.xml"/>
      5. </bean>

      4.1.3 类别名typeAliasesPackage

      MyBaits 别名包扫描路径,通过该属性可以给包中的类注册别名,注册后在 Mapper 对应的 XML ⽂件
      中可以直接使⽤类名,⽽不⽤使⽤全限定的类名(即 XML 中调⽤的时候不⽤包含包名)。
      springboot:
      1. mybatis-plus.type-aliases-package = com.atm.mp.pojo
      spring mvc:
      1. <bean id="sqlSessionFactory"
      2. class="com.baomidou.mybatisplus.extension.spring.MybatisSqlSessionFactoryBean"
      3. >
      4. <property name="typeAliasesPackage"
      5. value="com.baomidou.mybatisplus.samples.quickstart.entity"/>
      6. </bean>

      4.2 进阶配置

      4.2.1 驼峰转换mapUnderscoreToCamelCase

  • 类型:boolean
  • 默认值:true

是否开启⾃动驼峰命名规则(camel case)映射,即从经典数据库列名 A_COLUMN(下划线命名) 到
经典 Java 属性名 aColumn(驼峰命名) 的类似映射。

  1. #关闭⾃动驼峰映射,该参数不能和mybatis-plus.config-location同时存在
  2. mybatis-plus.configuration.map-underscore-to-camel-case=false

4.2.2 cacheEnabled

  • 类型:boolean
  • 默认值:true

全局地开启或关闭配置⽂件中的所有映射器已经配置的任何缓存,默认为 true。

  1. mybatis-plus.configuration.cache-enabled=false

4.3 DB配置

4.3.1 idType

  • 类型:com.baomidou.mybatisplus.annotation.IdType
  • 默认值:ID_WORKER

全局默认主键类型,设置后,即可省略实体对象中的@TableId(type = IdType.AUTO)配置。
springboot:

  1. mybatis-plus.global-config.db-config.id-type=auto

springmvc:

  1. <!--这⾥使⽤MP提供的sqlSessionFactory,完成了Spring与MP的整合-->
  2. <bean id="sqlSessionFactory"
  3. class="com.baomidou.mybatisplus.extension.spring.MybatisSqlSessionFactoryBean"
  4. >
  5. <property name="dataSource" ref="dataSource"/>
  6. <property name="globalConfig">
  7. <bean class="com.baomidou.mybatisplus.core.config.GlobalConfig">
  8. <property name="dbConfig">
  9. <bean
  10. class="com.baomidou.mybatisplus.core.config.GlobalConfig$DbConfig">
  11. <property name="idType" value="AUTO"/>
  12. </bean>
  13. </property>
  14. </bean>
  15. </property>
  16. </bean>

4.3.2 tablePrefix

  • 类型:string
  • 默认值: null

表名前缀,全局配置后可省略@TableName()配置。
springboot:

  1. mybatis-plus.global-config.db-config.table-prefix=tb_

spring mvc:

  1. <bean id="sqlSessionFactory"
  2. class="com.baomidou.mybatisplus.extension.spring.MybatisSqlSessionFactoryBean"
  3. >
  4. <property name="dataSource" ref="dataSource"/>
  5. <property name="globalConfig">
  6. <bean class="com.baomidou.mybatisplus.core.config.GlobalConfig">
  7. <property name="dbConfig">
  8. <bean
  9. class="com.baomidou.mybatisplus.core.config.GlobalConfig$DbConfig">
  10. <property name="idType" value="AUTO"/>
  11. <property name="tablePrefix" value="tb_"/>
  12. </bean>
  13. </property>
  14. </bean>
  15. </property>
  16. </bean>

5. 条件构造器

  1. 等式
  • eq:等于
  • ne:不等于
  • gt:大于
  • ge:大于等于
  • lt:小于
  • le:小于等于
  • between 值1 and 值2
  • not between 值1 and 值2
  • in:字段 in(value1,value2)
  • notIn:字段 not in(value1,value2)
  1. 模式查询
  • like:LIKE ‘%值%’
  • notLike:NOT LIKE ‘%值%’
  • likeLeft:LIKE ‘%值’
  • likeRight:LIKE ‘值%’
  1. 排序
  • orderBy
  • orderByAsc
  • orderByDesc
  1. 逻辑查询
  • or
    • 主动调⽤ or 表示紧接着下⼀个⽅法不是⽤ and 连接!(不调⽤ or 则默认为使⽤ and 连接)
  • and
    • AND 嵌套

      6. 插件