1. 程式人生 > 其它 >MyBatis-Plus基礎教程

MyBatis-Plus基礎教程

MyBatis-Plus

mybatis-plus 官網

1、簡介

1.1、特性

  • 無侵入:只做增強不做改變,引入它不會對現有工程產生影響,如絲般順滑

  • 損耗小:啟動即會自動注入基本 CURD,效能基本無損耗,直接面向物件操作

  • 強大的 CRUD 操作:內建通用 Mapper、通用 Service,僅僅通過少量配置即可實現單表大部分 CRUD 操作,更有強大的條件構造器,滿足各類使用需求

  • 支援 Lambda 形式呼叫:通過 Lambda 表示式,方便的編寫各類查詢條件,無需再擔心欄位寫錯

  • 支援主鍵自動生成:支援多達 4 種主鍵策略(內含分散式唯一 ID 生成器 - Sequence),可自由配置,完美解決主鍵問題

  • 支援 ActiveRecord 模式:支援 ActiveRecord 形式呼叫,實體類只需繼承 Model 類即可進行強大的 CRUD 操作

  • 支援自定義全域性通用操作:支援全域性通用方法注入( Write once, use anywhere )

  • 內建程式碼生成器:採用程式碼或者 Maven 外掛可快速生成 Mapper 、 Model 、 Service 、 Controller 層程式碼,支援模板引擎,更有超多自定義配置等您來使用

  • 內建分頁外掛:基於 MyBatis 物理分頁,開發者無需關心具體操作,配置好外掛之後,寫分頁等同於普通 List 查詢

  • 分頁外掛支援多種資料庫

    :支援 MySQL、MariaDB、Oracle、DB2、H2、HSQL、SQLite、Postgre、SQLServer 等多種資料庫

  • 內建效能分析外掛:可輸出 SQL 語句以及其執行時間,建議開發測試時啟用該功能,能快速揪出慢查詢

  • 內建全域性攔截外掛:提供全表 delete 、 update 操作智慧分析阻斷,也可自定義攔截規則,預防誤操作

1.2、框架結構

2、快速入門

2.1、mybatis實現查詢

專案結構

maven依賴

<dependencies>
    <!-- https://mvnrepository.com/artifact/com.baomidou/mybatis-plus -->
    <dependency>
        <groupId>com.baomidou</groupId>
        <artifactId>mybatis-plus</artifactId>
        <version>3.3.2</version>
    </dependency>
    <!-- https://mvnrepository.com/artifact/mysql/mysql-connector-java -->
    <dependency>
        <groupId>mysql</groupId>
        <artifactId>mysql-connector-java</artifactId>
        <version>8.0.16</version>
    </dependency>
    <!-- https://mvnrepository.com/artifact/com.alibaba/druid -->
    <dependency>
        <groupId>com.alibaba</groupId>
        <artifactId>druid</artifactId>
        <version>1.1.22</version>
    </dependency>
    <!-- https://mvnrepository.com/artifact/org.projectlombok/lombok -->
    <dependency>
        <groupId>org.projectlombok</groupId>
        <artifactId>lombok</artifactId>
        <version>1.18.12</version>
        <scope>provided</scope>
    </dependency>
    <dependency>
        <groupId>junit</groupId>
        <artifactId>junit</artifactId>
        <version>4.12</version>
        <scope>test</scope>
    </dependency>
</dependencies>

User.java

package com.example.pojo;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

/**
 * @author admin
 */
@Data
@NoArgsConstructor
@AllArgsConstructor
public class User {

    private int id;
    private String userName;
    private String password;
    private String name;
    private Integer age;
    private String email;
}

UserMapper.java

package com.example.mapper;

import com.example.pojo.User;

import java.util.List;

/**
 * @author admin
 */
public interface UserMapper {

    /**
     * 獲取全部使用者
     * @return
     */
    List<User> getAllUser();
}

db.properties

jdbc.driver=com.mysql.cj.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/test?characterEncoding=utf8&useSSL=true&serverTimezone=UTC
jdbc.username=root
jdbc.password=123456

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">
<configuration>
    <properties resource="db.properties"/>
    <settings>
        <setting name="logImpl" value="STDOUT_LOGGING"/>
    </settings>
    <typeAliases>
        <package name="com.example.pojo"/>
    </typeAliases>
    <environments default="development">
        <environment id="development">
            <transactionManager type="JDBC"/>
            <dataSource type="POOLED">
                <property name="driver" value="${jdbc.driver}"/>
                <property name="url" value="${jdbc.url}"/>
                <property name="username" value="${jdbc.username}"/>
                <property name="password" value="${jdbc.password}"/>
            </dataSource>
        </environment>
    </environments>
    <mappers>
        <mapper resource="UserMapper.xml"/>
    </mappers>
</configuration>

UserMapper.xml

<?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.example.mapper.UserMapper">
    <select id="getAllUser" resultType="user">
        select * from tb_user
    </select>
</mapper>

測試

package com.example.mapper;

import com.example.pojo.User;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.junit.Test;

import java.io.IOException;
import java.io.InputStream;
import java.util.List;

public class UserMapperTest {

    @Test
    public void testGetAllUser() throws IOException {
        InputStream stream = Resources.getResourceAsStream("mybatis-config.xml");
        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(stream);
        SqlSession sqlSession = sqlSessionFactory.openSession();
        UserMapper mapper = sqlSession.getMapper(UserMapper.class);
        List<User> userList = mapper.getAllUser();
        for (User user : userList) {
            System.out.println(user);
        }
        sqlSession.close();
    }
}

結果

2.2、mybatis-plus實現查詢

User.java

package com.example.pojo;

import com.baomidou.mybatisplus.annotation.TableName;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

/**
 * @TableName 指定該實體在資料庫中對映的表
 * @author admin
 */
@Data
@NoArgsConstructor
@AllArgsConstructor
@TableName("tb_user")
public class User {

    private int id;
    private String userName;
    private String password;
    private String name;
    private Integer age;
    private String email;
}

UserMapper.java

package com.example.mapper;

import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.example.pojo.User;

import java.util.List;

/**
 * @author admin
 */
public interface UserMapper extends BaseMapper<User> {

    /**
     * 獲取全部使用者
     * @return
     */
    List<User> getAllUser();
}

測試

@Test
public void testGetAllUserByMybatisPlus() throws IOException {
    InputStream stream = Resources.getResourceAsStream("mybatis-config.xml");
    SqlSessionFactory sqlSessionFactory = new MybatisSqlSessionFactoryBuilder().build(stream);
    SqlSession sqlSession = sqlSessionFactory.openSession();
    UserMapper mapper = sqlSession.getMapper(UserMapper.class);
    List<User> userList = mapper.selectList(null);
    for (User user : userList) {
        System.out.println(user);
    }
    sqlSession.close();
}

結果

2.3、spring + mybatis-plus 實現查詢

User.java

package com.example.pojo;

import com.baomidou.mybatisplus.annotation.TableName;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

/**
 * @author admin
 */
@Data
@AllArgsConstructor
@NoArgsConstructor
@TableName("tb_user")
public class User {
    private int id;
    private String userName;
    private String password;
    private String name;
    private Integer age;
    private String email;
}

UserMapper.java

package com.example.mapper;

import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.example.pojo.User;

/**
 * @author admin
 */
public interface UserMapper extends BaseMapper<User> {
}

jdbc.properties

jdbc.driver=com.mysql.cj.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/test?characterEncoding=utf8&useSSL=true&serverTimezone=UTC
jdbc.username=root
jdbc.password=123456

applicationContext.xml

<?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">

    <context:property-placeholder location="classpath:jdbc.properties"/>

    <bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource" destroy-method="close">
        <property name="driverClassName" value="${jdbc.driver}"/>
        <property name="url" value="${jdbc.url}"/>
        <property name="username" value="${jdbc.username}"/>
        <property name="password" value="${jdbc.password}"/>
        <property name="maxActive" value="10"/>
        <property name="minIdle" value="5"/>
    </bean>

    <bean id="sqlSessionFactory" class="com.baomidou.mybatisplus.extension.spring.MybatisSqlSessionFactoryBean">
        <property name="dataSource" ref="dataSource"/>
    </bean>

    <!--mapper介面掃描器-->
    <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
        <property name="basePackage" value="com.example.mapper"/>
    </bean>

</beans>

測試

package com.example.mapper;

import com.example.pojo.User;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
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 java.util.List;

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("classpath:applicationContext.xml")
public class UserMapperTest {

    @Autowired
    private SqlSessionFactory sqlSessionFactory;

    @Test
    public void testGetAllUser(){
        SqlSession sqlSession = sqlSessionFactory.openSession();
        UserMapper mapper = sqlSession.getMapper(UserMapper.class);
        List<User> userList = mapper.selectList(null);
        for (User user : userList) {
            System.out.println(user);
        }
        sqlSession.close();
    }
}

結果

2.4、springboot + mybatis-plus 實現查詢

專案結構

maven依賴

<dependencies>
    <!-- https://mvnrepository.com/artifact/com.baomidou/mybatis-plus-boot-starter -->
    <dependency>
        <groupId>com.baomidou</groupId>
        <artifactId>mybatis-plus-boot-starter</artifactId>
        <version>3.3.2</version>
    </dependency>

    <!-- https://mvnrepository.com/artifact/org.springframework.boot/spring-boot-starter-test -->
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-test</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter</artifactId>
    </dependency>

    <dependency>
        <groupId>mysql</groupId>
        <artifactId>mysql-connector-java</artifactId>
        <scope>runtime</scope>
    </dependency>
    <dependency>
        <groupId>org.projectlombok</groupId>
        <artifactId>lombok</artifactId>
        <optional>true</optional>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-test</artifactId>
        <scope>test</scope>
    </dependency>
</dependencies>

application.properties

spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
spring.datasource.url=jdbc:mysql://localhost:3306/test?characterEncoding=utf8&useSSL=true&serverTimezone=UTC
spring.datasource.username=root
spring.datasource.password=123456

User.java

package com.example.pojo;

import com.baomidou.mybatisplus.annotation.TableName;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

/**
 * @author admin
 */
@Data
@AllArgsConstructor
@NoArgsConstructor
@TableName("tb_user")
public class User {
    private int id;
    private String userName;
    private String password;
    private String name;
    private Integer age;
    private String email;
}

UserMapper.java

package com.example.mapper;

import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.example.pojo.User;
import org.apache.ibatis.annotations.Mapper;

/**
 * @author admin
 */
public interface UserMapper extends BaseMapper<User> {
}

SpringBoot啟動類

package com.example;

import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

/**
 * @author admin
 */
@SpringBootApplication
@MapperScan("com.example.mapper")
public class MybatisPlusSpringbootApplication {

    public static void main(String[] args) {
        SpringApplication.run(MybatisPlusSpringbootApplication.class, args);
    }

}

測試

package com.example;

import com.example.mapper.UserMapper;
import com.example.pojo.User;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;

import java.util.List;

@SpringBootTest
class MybatisPlusSpringbootApplicationTests {

    @Autowired(required = false)
    private UserMapper userMapper;

    @Test
    void contextLoads() {
        List<User> userList = userMapper.selectList(null);
        for (User user : userList) {
            System.out.println(user);
        }
    }

}

結果

3、通用CRUD

3.1、插入

User.java

package com.example.pojo;

import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableName;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

/**
 * @author admin
 */
@Data
@AllArgsConstructor
@NoArgsConstructor
@TableName("tb_user")
public class User {
    @TableId(type = IdType.AUTO)
    private int id;
    private String userName;
    private String password;
    private String name;
    private Integer age;
    private String email;
}

測試

@Test
public void testInsert(){
    User user = new User();
    user.setUserName("simayi");
    user.setPassword("666666");
    user.setName("司馬懿");
    user.setAge(31);
    user.setEmail("[email protected]");
    int row = userMapper.insert(user);
    System.out.println("資料庫中受影響的行數: "+row);
    //自增後的id會回填到物件中
    int id = user.getId();
    System.out.println("自增長後的id值: "+id);
}

3.2、@TableField

在mybatis-plus中通過@TableField註解可以指定欄位的一些屬性,常常解決的問題有2個:

  1. 物件中的屬性名和欄位名不一致的問題(非駝峰)
  2. 物件中的屬性欄位在表中不存在的問題

資料庫中的tb_user表

實體對映User

解決問題1:

package com.example.pojo;

import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableField;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableName;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

/**
 * @author admin
 */
@Data
@AllArgsConstructor
@NoArgsConstructor
@TableName("tb_user")
public class User {
    @TableId(type = IdType.AUTO)
    private int id;
    private String userName;
    private String password;
    private String name;
    private Integer age;
    //指定資料庫中的欄位
    @TableField("email")
    private String mail;
}

解決問題2:

package com.example.pojo;

import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableField;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableName;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

/**
 * @author admin
 */
@Data
@AllArgsConstructor
@NoArgsConstructor
@TableName("tb_user")
public class User {
    @TableId(type = IdType.AUTO)
    private int id;
    private String userName;
    private String password;
    private String name;
    private Integer age;
    private String email;

    /**
     * 表明該屬性在資料庫中不存在
     */
    @TableField(exist = false)
    private String address;
}

查詢時不返回指定欄位的值

package com.example.pojo;

import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableField;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableName;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

/**
 * @author admin
 */
@Data
@AllArgsConstructor
@NoArgsConstructor
@TableName("tb_user")
public class User {
    @TableId(type = IdType.AUTO)
    private int id;
    private String userName;
    
    /**
     * 查詢時不返回該欄位的值
     */
    @TableField(select = false)
    private String password;
    private String name;
    private Integer age;
    private String email;
}

3.3、更新

3.3.1、根據id更新

測試

@Test
public void testUpdateById(){
    User user = new User();
    user.setId(7);
    user.setPassword("777777");
    int row = userMapper.updateById(user);
    System.out.println("資料庫中受影響的行數: "+row);
    testSelectById();
}

@Test
public void testSelectById(){
    User user = userMapper.selectById(7);
    System.out.println(user);
}

結果

3.3.2、根據條件更新

測試

方法一:

@Test
public void testUpdateByCondition_1(){
    User user = new User();
    user.setAge(18);
    QueryWrapper<User> wrapper = new QueryWrapper<>();
    //匹配user_name等於zhangsan的使用者資料
    wrapper.eq("user_name","zhangsan");
    int row = userMapper.update(user, wrapper);
    System.out.println("資料庫中受影響的行數: "+row);
}

方法二:

@Test
public void testUpdateByCondition_2(){
    UpdateWrapper<User> wrapper = new UpdateWrapper<>();
    wrapper.set("age",18).eq("user_name","zhangsan");
    int row = userMapper.update(null, wrapper);
    System.out.println("資料庫中受影響的行數: "+row);
}

3.4、刪除

3.4.1、根據id刪除

測試

@Test
public void testDeleteById(){
    int row = userMapper.deleteById(100);
    System.out.println("資料庫中受影響的行數: "+row);
}

3.4.2、根據條件刪除

測試

方法一:

@Test
public void testDeleteByMap(){
    Map<String,Object> map=new HashMap<>();
    map.put("user_name","zhangsan");
    map.put("password","999999");
    //根據map刪除資料,多條件之間是and關係
    int row = userMapper.deleteByMap(map);
    System.out.println("資料庫中受影響的行數: "+row);
}

方法二:

@Test
public void testDelete_1(){
    QueryWrapper<User> wrapper = new QueryWrapper<>();
    wrapper.eq("user_name","zhangsan").eq("password","999999");
    int row = userMapper.delete(wrapper);
    System.out.println("資料庫中受影響的行數: "+row);
}

方法三:

@Test
public void testDelete_2(){
    User user = new User();
    user.setUserName("zhangsan");
    user.setPassword("000000");
    QueryWrapper<User> wrapper = new QueryWrapper<>(user);
    int row = userMapper.delete(wrapper);
    System.out.println("資料庫中受影響的行數: "+row);
}

3.4.3、根據id批量刪除

測試

@Test
public void testDeleteBatchIds(){
    //根據id批量刪除記錄
    int row = userMapper.deleteBatchIds(Arrays.asList(100, 200, 300, 400, 500));
    System.out.println("資料庫中受影響的行數: "+row);
}

3.5、查詢

3.5.1、根據id查詢

測試

@Test
public void testSelectById(){
    User user = userMapper.selectById(7);
    System.out.println(user);
}

3.5.2、根據id批量查詢

測試

@Test
public void testSelectBatchIds(){
    List<User> userList = userMapper.selectBatchIds(Arrays.asList(1, 2, 3, 100));
    for (User user : userList) {
        System.out.println(user);
    }
}

3.5.3、根據條件查詢

根據條件查詢單條記錄

@Test
public void testSelectOne(){
    QueryWrapper<User> wrapper = new QueryWrapper<>();
    wrapper.eq("user_name","zhaoliu");
    User user = userMapper.selectOne(wrapper);
    System.out.println(user);
}

注意:若查詢結果包含多條記錄則報錯

根據條件查詢多條記錄

@Test
public void testSelectList(){
    QueryWrapper<User> wrapper = new QueryWrapper<>();
    //wrapper.gt("age",25);
    //查詢郵箱中包含z的使用者
    wrapper.like("email","z");
    List<User> userList = userMapper.selectList(wrapper);
    for (User user : userList) {
        System.out.println(user);
    }
}

3.5.4、查詢記錄的條數

測試

@Test
public void testSelectCount(){
    QueryWrapper<User> wrapper = new QueryWrapper<>();
    //查詢年齡大於20歲的使用者
    wrapper.gt("age",20);
    Integer count = userMapper.selectCount(wrapper);
    System.out.println("年齡大於20歲的使用者有"+count+"個");
}

3.5.5、分頁查詢

MybatisPlusConfig.java

package com.example;

import com.baomidou.mybatisplus.extension.plugins.PaginationInterceptor;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * @author admin
 */
@Configuration
@MapperScan("com.example.mapper")
public class MybatisPlusConfig {

    /**
     * 配置分頁外掛
     * @return
     */
    @Bean
    public PaginationInterceptor paginationInterceptor(){
        return new PaginationInterceptor();
    }
}

測試

@Test
public void testSelectPage(){
    //查詢第一頁,每頁3條資料
    Page<User> page = new Page<>(1,3);
    QueryWrapper<User> wrapper = new QueryWrapper<>();
    wrapper.gt("age","20");
    Page<User> userPage = userMapper.selectPage(page, wrapper);
    System.out.println("資料總條數: "+userPage.getTotal());
    System.out.println("資料總頁數: "+userPage.getPages());
    System.out.println("當前頁數: "+userPage.getCurrent());
    List<User> userList = userPage.getRecords();
    for (User user : userList) {
        System.out.println(user);
    }
}

4、配置

4.1、configLocation

springboot:

mybatis-plus.config-location=classpath:mybatis-config.xml

springmvc:

<bean id="sqlSessionFactory" class="com.baomidou.mybatisplus.extension.spring.MybatisSqlSessionFactoryBean">
	<property name="configLocation" value="classpath:mybatis-config.xml"/>
</bean>

4.2、mapperLocations

springboot:

mybatis-plus.mapper-locations=classpath:mybatis/*.xml

springmvc:

<bean id="sqlSessionFactory" class="com.baomidou.mybatisplus.extension.spring.MybatisSqlSessionFactoryBean">
	<property name="mapperLocations" value="classpath:mybatis/*.xml"/>
</bean>

4.3、typeAliasesPackage

springboot:

mybatis-plus.type-aliases-package=com.example.pojo

springmvc:

<bean id="sqlSessionFactory" class="com.baomidou.mybatisplus.extension.spring.MybatisSqlSessionFactoryBean">
	<property name="typeAliasesPackage" value="com.example.pojo"/>
</bean>

4.4、mapUnderscoreToCamelCase

  • 型別:boolean
  • 預設值:true

是否開啟自動駝峰命名規則對映,即從經典資料庫列名a_column(下劃線命名)到經典Java屬性名aColumn(駝峰命名)的類似對映。

注意:

此屬性在MyBatis中原預設值為false,在MyBatis-Plus中,此屬性也將用於生成最終的sql的select body

如果你的資料庫命名符合規則則無需使用@TableField註解指定資料庫欄位名

mybatis-plus.configuration.*和mybatis-plus.config-location不能同時出現在配置檔案中

springboot:

mybatis-plus.configuration.map-underscore-to-camel-case=false

4.5、cacheEnabled

  • 型別:boolean
  • 預設值:true

全域性地開啟或關閉配置檔案中的所有對映器已經配置的任何快取,預設為true。

springboot:

mybatis-plus.configuration.cache-enabled=false

4.6、idType

  • 型別:com.baomidou.mybatisplus.annotation.IdType
  • 預設值:ID_WORKER

全域性預設主鍵型別,設定後,即可省略實體物件中的@TableId(type = IdType.AUTO)配置

springboot:

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

springmvc:

<bean id="sqlSessionFactory" class="com.baomidou.mybatisplus.extension.spring.MybatisSqlSessionFactoryBean">
	<property name="globalConfig">
    	<bean class="com.baomidou.mybatisplus.core.config.GlobalConfig">
        	<property name="dbConfig">
            	<bean class="com.baomidou.mybatisplus.core.config.GlobalConfig$DbConfig">
                	<property name="idType" value="AUTO"/>
                </bean>
            </property>
        </bean>
    </property>
</bean>

4.7、tablePrefix

  • 型別:String
  • 預設值:null

表名字首,全域性配置後可省略@TableName()配置

springboot:

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

springmvc:

<bean id="sqlSessionFactory" class="com.baomidou.mybatisplus.extension.spring.MybatisSqlSessionFactoryBean">
	<property name="globalConfig">
    	<bean class="com.baomidou.mybatisplus.core.config.GlobalConfig">
        	<property name="dbConfig">
            	<bean class="com.baomidou.mybatisplus.core.config.GlobalConfig$DbConfig">
                	<property name="tablePrefix" value="tb_"/>
                </bean>
            </property>
        </bean>
    </property>
</bean>

5、條件構造器

說明:

  • 以下出現的第一個入參boolean condition表示該條件是否加入最後生成的sql中,例如:query.like(StringUtils.isNotBlank(name), Entity::getName, name) .eq(age!=null && age >= 0, Entity::getAge, age)
  • 以下程式碼塊內的多個方法均為從上往下補全個別boolean型別的入參,預設為true
  • 以下出現的泛型Param均為Wrapper的子類例項(均具有AbstractWrapper的所有方法)
  • 以下方法在入參中出現的R為泛型,在普通wrapper中是String,在LambdaWrapper中是函式(例:Entity::getId,Entity為實體類,getId為欄位idgetMethod)
  • 以下方法入參中的R column均表示資料庫欄位,當R具體型別為String時則為資料庫欄位名(欄位名是資料庫關鍵字的自己用轉義符包裹!)!而不是實體類資料欄位名!!!,另當R具體型別為SFunction時專案runtime不支援eclipse自家的編譯器!!!
  • 以下舉例均為使用普通wrapper,入參為MapList的均以json形式表現!
  • 使用中如果入參的Map或者List,則不會加入最後生成的sql中!!!
  • 有任何疑問就點開原始碼看,看不懂函式點選我學習新知識(opens new window)

警告:

不支援以及不贊成在 RPC 呼叫中把 Wrapper 進行傳輸

  1. wrapper 很重
  2. 傳輸 wrapper 可以類比為你的 controller 用 map 接收值(開發一時爽,維護火葬場)
  3. 正確的 RPC 呼叫姿勢是寫一個 DTO 進行傳輸,被呼叫方再根據 DTO 執行相應的操作
  4. 我們拒絕接受任何關於 RPC 傳輸 Wrapper 報錯相關的 issue 甚至 pr

AbstractWrapper

說明:

QueryWrapper(LambdaQueryWrapper) 和 UpdateWrapper(LambdaUpdateWrapper) 的父類
用於生成 sql 的 where 條件, entity 屬性也用於生成 sql 的 where 條件
注意: entity 生成的 where 條件與 使用各個 api 生成的 where 條件沒有任何關聯行為

5.1、allEq

測試

@Test
public void testAllEq(){
    Map<String,Object> map=new HashMap<>();
    map.put("name","李四");
    map.put("age",20);
    map.put("password",null);
    QueryWrapper<User> wrapper = new QueryWrapper<>();
    //null值作為查詢條件:SELECT id,user_name,password,name,age,email FROM tb_user WHERE (password IS NULL AND name = ? AND age = ?)
    //wrapper.allEq(map);
    //null值不作為查詢條件:SELECT id,user_name,password,name,age,email FROM tb_user WHERE (name = ? AND age = ?)
    //wrapper.allEq(map,false);
    //SELECT id,user_name,password,name,age,email FROM tb_user WHERE (age = ?) 
    wrapper.allEq((k,v)->(k.equals("age") || k.equals("id")), map);
    List<User> userList = userMapper.selectList(wrapper);
    for (User user : userList) {
        System.out.println(user);
    }
}

5.2、基本比較操作

  • eq:等於 =
  • ne:不等於 <>
  • gt:大於 >
  • ge:大於等於 >=
  • lt:小於 <
  • le:小於等於 <=
  • between:between 值1 and 值2
  • notBetween:not between 值1 and 值2
  • in:欄位 in (value.get(0), value.get(1), ...)
  • notIn:欄位 not in (v0, v1, ...)

測試

@Test
public void testBasicConditionStructure(){
    QueryWrapper<User> wrapper = new QueryWrapper<>();
    //SELECT id,user_name,password,name,age,email FROM tb_user WHERE (password = ? AND age >= ? AND name IN (?,?,?)) 
    wrapper.eq("password","222222")
            .ge("age",20)
            .in("name","張三","李四","王五");
    List<User> userList = userMapper.selectList(wrapper);
    for (User user : userList) {
        System.out.println(user);
    }
}

5.3、模糊查詢

  • like
    • like '%值%'
    • 例:like("name", "王")--->namelike'%王%'
  • notLike
    • not like '%值%'
    • 例:notLike("name", "王")--->namenotlike'%王%'
  • likeLeft
    • like '%值'
    • 例:likeLeft("name", "王")--->namelike'%王'
  • likeRight
    • like '值%'
    • 例:likeRight("name", "王")--->namelike'王%'

測試

@Test
public void testLike(){
    QueryWrapper<User> wrapper = new QueryWrapper<>();
    wrapper.likeLeft("name","五");
    List<User> userList = userMapper.selectList(wrapper);
    for (User user : userList) {
        System.out.println(user);
    }
}

5.4、排序

  • orderBy
    • 排序:order by 欄位, ...
    • 例:orderBy(true, true, "id", "name")--->order byidASC,nameASC
  • orderByAsc
    • 排序:order by 欄位, ... ASC
    • 例:orderByAsc("id", "name") ---> order by id ASC,name ASC
  • orderByDesc
    • 排序:order by 欄位, ... desc
    • 例:orderByDesc("id", "name")--->orderbyiddesc,namedesc

測試

@Test
public void testOrderByDesc(){
    QueryWrapper<User> wrapper = new QueryWrapper<>();
    //按照年齡倒序排序:SELECT id,user_name,password,name,age,email FROM tb_user ORDER BY age DESC 
    wrapper.orderByDesc("age");
    List<User> userList = userMapper.selectList(wrapper);
    for (User user : userList) {
        System.out.println(user);
    }
}

5.5、邏輯查詢

  • or
    • 拼接 or
    • 主動呼叫or表示緊接著下一個方法不是用and連線!(不呼叫or則預設為使用and連線)
  • and
    • and 巢狀
    • 例:and(i -> i.eq("name", "張三").gt("age", 20)) --->and(name = '張三' and age > 20)

測試

@Test
public void testOr(){
    QueryWrapper<User> wrapper = new QueryWrapper<>();
    //SELECT id,user_name,password,name,age,email FROM tb_user WHERE (name = ? OR age = ?) 
    wrapper.eq("name","王五").or().eq("age",21);
    List<User> userList = userMapper.selectList(wrapper);
    for (User user : userList) {
        System.out.println(user);
    }
}

5.6、select

在mybatis-plus查詢中,預設查詢所有的欄位,如果有需要也可以通過select方法進行指定欄位。

測試

@Test
public void testSelect(){
    QueryWrapper<User> wrapper = new QueryWrapper<>();
    //SELECT id,name,age FROM tb_user 
    wrapper.select("id","name","age");
    List<User> userList = userMapper.selectList(wrapper);
    for (User user : userList) {
        System.out.println(user);
    }
}

6、ActiveRecord

ActiveRecord(簡稱AR)一直廣受動態語言(PHP、Ruby等)的喜愛,而Java作為準靜態語言,對於ActiveRecord往往只能感嘆其優雅,所以我們也在AR道路上進行了一定的探索。

什麼是ActiveRecord?

ActiveRecord也屬於ORM(物件關係對映)層,由Reils最早提出,遵循標準的ORM模型:表對映到記錄,記錄對映到物件,欄位對映到物件屬性。配合遵循的命名和配置慣例,能夠很大程度的快速實現模型的操作,而且簡潔易懂。

ActiveRecord的主要思想是:

  • 每一個數據庫表對應建立一個類,類的每一個物件例項對應於資料庫中表的一行記錄;通常表的每個欄位在類中都有相應的Field;
  • ActiveRecord同時負責把自己持久化,在ActiveRecord中封裝了對資料庫的訪問,即CURD;
  • ActiveRecord是一種領域模型(Domain Model),封裝了部分業務邏輯;

6.1、根據主鍵查詢

User.java

package com.example.pojo;

import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableField;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableName;
import com.baomidou.mybatisplus.extension.activerecord.Model;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

/**
 * @author admin
 */
@Data
@AllArgsConstructor
@NoArgsConstructor
@TableName("tb_user")
public class User extends Model<User> {
    @TableId(type = IdType.AUTO)
    private int id;
    private String userName;
    private String password;
    private String name;
    private Integer age;
    private String email;
}

測試

package com.example;

import com.example.pojo.User;
import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;

@SpringBootTest
public class UserTest {

    @Test
    public void testSelectById(){
        User user = new User();
        user.setId(3);
        User userById = user.selectById();
        System.out.println(userById);
    }
}

結果

6.2、插入

User.java

package com.example.pojo;

import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableField;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableName;
import com.baomidou.mybatisplus.extension.activerecord.Model;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

/**
 * @author admin
 */
@Data
@AllArgsConstructor
@NoArgsConstructor
@TableName("tb_user")
public class User extends Model<User> {
    @TableId(type = IdType.AUTO)
    private int id;
    private String userName;
    private String password;
    private String name;
    private Integer age;
    private String email;
}

測試

@Test
public void testInsert(){
    User user = new User();
    user.setUserName("pangtong");
    user.setPassword("888888");
    user.setName("龐統");
    user.setAge(36);
    user.setEmail("[email protected]");
    boolean isInsert = user.insert();
    System.out.println("插入是否成功: "+isInsert);
}

6.3、更新

6.3.1、根據id更新

@Test
public void testUpdateById(){
    User user = new User();
    //查詢條件
    user.setId(10);
    //更新的資料
    user.setAge(100);
    boolean isUpdate = user.updateById();
    System.out.println("更新是否成功: "+isUpdate);
}

6.3.2、根據條件更新

@Test
public void testUpdate(){
    User user = new User();
    UpdateWrapper<User> wrapper = new UpdateWrapper<>();
    wrapper.eq("name","太史特").set("age",100);
    boolean isUpdate = user.update(wrapper);
    System.out.println("更新是否成功: "+isUpdate);
}

6.4、刪除

6.4.1、根據id刪除

@Test
public void testDeleteById(){
    User user = new User();
    boolean isDelete = user.deleteById(100);
    System.out.println("刪除是否成功: "+isDelete);
}

6.4.2、根據條件刪除

@Test
public void testDelete(){
    User user = new User();
    QueryWrapper<User> wrapper = new QueryWrapper<>();
    wrapper.eq("name","太史特");
    boolean isDelete = user.delete(wrapper);
    System.out.println("刪除是否成功: "+isDelete);
}

6.5、根據條件查詢

@Test
public void testSelectList(){
    User user = new User();
    QueryWrapper<User> wrapper = new QueryWrapper<>();
    //查詢年齡大於等於30歲的使用者
    wrapper.ge("age",30);
    List<User> userList = user.selectList(wrapper);
    for (User user1 : userList) {
        System.out.println(user1);
    }
}
作者:(x²+y²-1)³=x²y³ 出處:http://www.cnblogs.com/yts-helloworld/

-------------------------------------------

個性簽名:獨學而無友,則孤陋而寡聞。做一個靈魂有趣的人!

如果覺得這篇文章對你有小小的幫助的話,記得在右下角點個“推薦”哦,博主在此感謝!

萬水千山總是情,打賞一分行不行,所以如果你心情還比較高興,也是可以掃碼打賞博主,哈哈哈(っ•̀ω•́)っ✎⁾⁾!