Mybatis-plus基本用法


1.簡介

官網:https://mp.baomidou.com

MyBatis-Plus(簡稱 MP)是一個 MyBatis 的增強工具,在 MyBatis 的基礎上只做增強不做改變,為簡化開發、提高效率而生。

2.入門

源碼:https://github.com/zhongyushi-git/mybatis-plus-demo.git

2.1數據庫准備

使用mysql數據庫創建數據,執行腳本在根目錄下的sql目錄下

2.2環境搭建

1)新建一個SpringBoot的項目,導入需要的坐標

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <!--mysql數據庫依賴-->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <scope>runtime</scope>
        </dependency>
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>druid</artifactId>
            <version>1.1.9</version>
        </dependency>
        <!--lombok-->
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <version>1.18.8</version>
        </dependency>

2)yml配置

#數據源配置
spring:
  datasource:
    #使用阿里巴巴的druid
    type: com.alibaba.druid.pool.DruidDataSource
    #配置數據庫的路徑和用戶名密碼
    url: jdbc:mysql://127.0.0.1:3306/mybatisplus?useUnicode=true&characterEncoding=UTF-8&serverTimezone=CTT&zeroDateTimeBehavior=convertToNull&useSSL=false&allowMultiQueries=true
    username: root
    password: zys123456

2.3引入mybatis-plus開發

1)導入依賴

      <!--mybatis-plus-->
        <dependency>
            <groupId>com.baomidou</groupId>
            <artifactId>mybatis-plus-boot-starter</artifactId>
            <version>3.4.0</version>
        </dependency>

2)創建實體類

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

3)創建dao繼承BaseMapper

package com.zys.mybatisplusdemo.dao;

import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.zys.mybatisplusdemo.entity.User;

public interface UserDao extends BaseMapper<User> {

}

4)在啟動類上加mapper掃描

@SpringBootApplication
@MapperScan("com.zys.mybatisplusdemo.dao")
public class MybatisPlusDemoApplication {

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

}

5)創建controller

@RestController
@RequestMapping("/users")
public class UserController {

    @Autowired
    private UserDao userDao;

    @GetMapping("/list")
    public List<User> userList(){
        List<User> users = userDao.selectList(null);
        return  users;
    }
}

為了演示方便,這里省略了service的部分而直接調用了dao層,具體見源碼。

如果添加了mapper.xml,那么需要配置xml的位置,否則會出現無法綁定。

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

6)測試

啟動項目,訪問http://localhost:8080/users/list即可看到所有的數據。

3.常用注解

3.1@TableName

其用來將實體對象與數據庫表名進行對應。當實體名與數據庫表名不一致時使用。

3.2@TableId

其是主鍵注解,指明是主鍵,默認把id作為主鍵。屬性type用來指定類型:

1)IdType.AUTO是自動增長;

2)IdType.ASSIGN_UUID是String類型的uuid

3)IdType.INPUT是根據用戶的輸入作為主鍵

3.3@TableField

其是表的其他字段注解。屬性exist用來指明是否是數據庫的字段,值為false時不映射數據庫表字段。詳細的介紹見后續章節,這里的說明已供使用。

3.4注解開發

1)首先將數據庫中表名改為t_user,然后實體User加上注解@TableName

@Data
@TableName(value = "t_user")
public class User {
     ......      
}

啟動項目,訪問http://localhost:8080/users/list可以正常返回數據。

2)將數據庫中表t_user的字段id改為t_id,然后修改實體User的屬性id並設置自動增長

@Data
@TableName(value = "t_user")
public class User {
    //指定自動增長
    @TableId(value = "t_id",type = IdType.AUTO)
    private Long id;
    ......
}

3)將數據表t_user的字段name改為t_name,然后修改實體User的屬性name

 @TableField(value = "t_name")
 private String name;

4)在實體User上添加一個屬性,設置不作為數據庫的字段

 //不映射數據庫表字段
    @TableField(exist = false)
    private String aaa;

啟動項目,同上進行訪問,數據正常返回。在實際開發過程中,可根據需求使用注解。

4.條件構造器

方法 說明 示例
eq 等於

allEq({id:1,name:"老王",age:null})--->

id = 1 and name = '老王' and age is null

allEq 全等於 eq("name", "老王")--->name = '老王'
ne 不等於 ne("name", "老王")--->name <> '老王'
gt 大於 gt("age", 18)--->age > 18
ge 大於等於 ge("age", 18)--->age >= 18
lt 小於 lt("age", 18)--->age < 18
le 小於等於 le("age", 18)--->age <= 18
between BETWEEN 值1 AND 值2 between("age", 18, 30)--->age between 18 and 30
notBetween NOT BETWEEN 值1 AND 值2 notBetween("age", 18, 30)--->age not between 18 and 30
like LIKE '%值%' like("name", "王")--->name like '%王%'
notLike NOT LIKE '%值%' notLike("name", "王")--->name not like '%王%'
likeLeft LIKE '%值' likeLeft("name", "王")--->name like '%王'
likeRight LIKE '值%' likeRight("name", "王")--->name like '王%'
isNull 字段為null isNull("name")--->name is null
isNotNull 字段不為null isNotNull("name")--->name is not null
in 同數據庫in in("age",{1,2,3})--->age in (1,2,3)
notIn 同數據庫not in notIn("age",{1,2,3})--->age not in (1,2,3)
inSql 相當於子查詢和in

inSql("id", "select id from table where id < 3")--->

id in (select id from table where id < 3)

notInSql 相當於子查詢和not in

notInSql("id", "select id from table where id < 3")--->

id not in (select id from table where id < 3)

groupBy 同數據庫group by groupBy("id", "name")--->group by id,name
orderBy/orderByDesc 同數據庫order by 字段/order by  字段 desc orderBy("id")--->order by id ASC
having 同數據庫having having("sum(age) > 10")--->having sum(age) > 10
or/and 同數據庫or/and 略 
netsted 正常嵌套 不帶 AND 或者 OR nested(i -> i.eq("name", "李白").ne("status", "活着"))--->(name = '李白' and status <> '活着')
apply 字符串拼接

apply("date_format(dateColumn,'%Y-%m-%d') = {0}", "2008-08-08")--->

date_format(dateColumn,'%Y-%m-%d') = '2008-08-08'")

last 拼接在最后,謹慎使用 last("limit 1")---> limit 1
exists/notExists 拼接sql exists("select id from table where age = 1")--->exists (select id from table where age = 1)
select 指定要查詢的字段 select("id", "name", "age")--->只查詢這三個字段的內容
set 全局修改 set("name", "")--->數據庫字段值變為空字符串

5.CRUD操作

只進行簡單的介紹,具體需求請自行開發,都是在這個基礎上進行的。需要說明的是,下面的增加和修改操作,只會根據對象中存在不為null的屬性來操作數據,當數據為null時不會改變數據庫中的數據。

5.1添加insert

    @PostMapping("/")
    public String save(User user){
        int count = userDao.insert(user);
        if(count!=0){
            return "添加成功";
        }else{
            return "添加失敗";
        }
    }

5.2刪除delete

根據主鍵刪除

  @DeleteMapping("/{id}")
    public String delete(@PathVariable("id")long id){
        int count = userDao.deleteById(id);
        if(count!=0){
            return "刪除成功";
        }else{
            return "刪除失敗";
        }
    }

5.3修改update

根據id進行修改

@PutMapping("/")
    public String update(User user){
        int count = userDao.updateById(user);
        if(count!=0){
            return "修改成功";
        }else{
            return "修改失敗";
        }
    }

5.4簡單查詢

5.4.1selectList

在入門時,controller中設置的查詢條件是null,實際上里面需要傳遞一個QueryWrapper<T>類型的對象,調用dao的selectList(),此對象中才有上面的那些方法。

1)查詢年齡大於等於24的信息

    @GetMapping("/list")
    public List<User> userList(){ QueryWrapper<User> queryWrapper = new QueryWrapper<>(); //設置查詢條件 queryWrapper.ge("age",24);//查詢年齡大於等於24的信息 List<User> users = userDao.selectList(queryWrapper); return users; }

2)查詢名字中含有‘o’的信息

queryWrapper.like("name","o");

5.4.2selectById

根據主鍵查詢

 @GetMapping("/{id}")
    public User selectById(@PathVariable("id")long id){ return userDao.selectById(id); }

5.4.3selectCount

查詢符合條件的條數,一般和selectList結合使用。

 @GetMapping("/list")
    public Map<String,Object> userList(){ QueryWrapper<User> queryWrapper = new QueryWrapper<>(); //設置查詢條件 queryWrapper.like("name","o"); List<User> users = userDao.selectList(queryWrapper); Integer integer = userDao.selectCount(queryWrapper); Map<String,Object> map=new HashMap<>(); map.put("data",users); map.put("total",integer); return map; }

5.5分頁查詢

5.5.1分頁插件配置

新建一個類配置其分頁

package com.zys.mybatisplusdemo.config;

import com.baomidou.mybatisplus.extension.plugins.PaginationInterceptor;
import com.baomidou.mybatisplus.extension.plugins.pagination.optimize.JsqlParserCountOptimize;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.transaction.annotation.EnableTransactionManagement;

/**
 * @Aauthor yushizhong
 * @Date 2020/5/17 16:19
 * @Dec MybatisPlus分頁配置
 */
@EnableTransactionManagement
@Configuration
@MapperScan("com.zys.mybatisplusdemo.dao")
public class MybatisPlusConfig {

    @Bean
    public PaginationInterceptor paginationInterceptor() {
        PaginationInterceptor paginationInterceptor = new PaginationInterceptor();
        return paginationInterceptor;
    }
}

5.5.2單表分頁查詢

@GetMapping("/list")
    public IPage<User> userList(Integer curr,Integer limit){
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        //設置分頁,默認值是1,10
        IPage<User> page=new Page<>(curr,limit);
        IPage<User> user = userDao.selectPage(page, queryWrapper);
        return  user;
    }

5.5.3單表自定義分頁查詢

有時使用默認的分頁查詢無法實現需要的功能時,可以自定義分頁查詢。

先分析一下其自帶的分頁的方法,打開源碼,看到接口中的selectPage方法:

<E extends com.baomidou.mybatisplus.core.metadata.IPage<T>> E selectPage(E page,
@org.apache.ibatis.annotations.Param("ew") com.baomidou.mybatisplus.core.conditions.Wrapper<T> queryWrapper);

那么自定義也就是模仿其寫法,步驟如下:

1)在dao的接口中定義方法

 IPage<User> selectPageList(IPage<User> page, @Param(Constants.WRAPPER) QueryWrapper<User> queryWrapper);

對第二個參數queryWrapper使用了@Param注解起別名,其名稱使用的是常量的值(實際值是ew),常量的定義也是由官方定義好的,截圖如下:

2)在xml中編寫sql

    <select id="selectPageList" resultType="com.zys.mybatisplusdemo.entity.User">
        select * from user ${ew.customSqlSegment}
    </select>

那么后面的條件就直接使用"${ew.customSqlSegment}"進行代替了,它會根據設置的條件去查詢。

5.5.4多表自定義分頁查詢

多表分頁和單表的分頁原來是一樣的道理。現假設有兩個表,t_student(學生表)和t_clazz(班級表)

1)先創建兩個表

CREATE TABLE `clazz` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `name` varchar(50) DEFAULT NULL COMMENT '班級名稱',
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=4 DEFAULT CHARSET=utf8;

CREATE TABLE `student` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `name` varchar(20) DEFAULT NULL COMMENT '學生姓名',
  `clazzId` int(11) DEFAULT NULL COMMENT '班級id',
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=7 DEFAULT CHARSET=utf8;

insert into clazz values(1,'計算機1班'),(2,'計算機2班'),(3,'計算機3班');
insert into student values(null,'趙敏',1),(null,'張明',3),(null,'李慧',3),(null,'趙美美',2),(null,'張峰',2),(null,'孫強',2);

2)創建學生實體類

@Data
@TableName(value = "user")
public class Student {

    @TableId(value = "id",type = IdType.AUTO)
    private Long id;

    @TableField(value = "name")
    private String name;

    @TableField(value = "clazzId")
    private Integer clazzId;

    @TableField(exist = false)
    private String clazzName;
}

3)創建controller接口

    @GetMapping("/list")
    public JSONObject getList(Integer curr, Integer limit) {
        QueryWrapper<Student> queryWrapper = new QueryWrapper<>();
        queryWrapper.like("t1.name", "");
        IPage<Student> page = new Page<>(curr, limit);
        IPage<Student> stu = studentDao.selectPageList(page, queryWrapper);
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("data", stu.getRecords());
        jsonObject.put("total", stu.getTotal());
        return jsonObject;
        
    }

4)在dao接口定義方法

IPage<Student> selectPageList(IPage<Student> page, @Param(Constants.WRAPPER) QueryWrapper<Student> queryWrapper);

5)在xml編寫sql

<select id="selectPageList" resultType="com.zys.mybatisplusdemo.entity.Student">
        select t1.*,t2.name "clazzName" from student t1
        left join clazz t2 on t1.clazzId = t2.id
         ${ew.customSqlSegment}
</select>

6)調用此接口,數據可以正常查詢。執行日志如下:

當然,對於多表查詢,如果使用默認的條件查詢不能滿足要求,可以把QueryMapper換成Mmap,那么在xml中使用對應的參數查詢即可。 不過這種方式有些麻煩,但是可以實現更為復雜的需求

dao接口的方法:

IPage<Student> selectPageList2(IPage<Student> page, @Param(Constants.WRAPPER)Map<String, Object> map);

xml的sql:

<select id="selectPageList2" resultType="com.zys.mybatisplusdemo.entity.Student">
        select t1.*, t2.name "clazzName"
        from student t1
                 left join clazz t2 on t1.clazzId = t2.id
        where t1.name like '%' || #{ew.name} ||'%'
</select>

6.代碼生成器

代碼生成器自動生成包及需要的類名,節省開發的時間。前提是數據庫中表已經建好,原因是它根據數據庫表進行創建的。

首先導入依賴

     <!--mybatis-plus代碼生成器-->
        <dependency>
            <groupId>com.baomidou</groupId>
            <artifactId>mybatis-plus-generator</artifactId>
            <version>3.4.0</version>
        </dependency>
        <dependency>
            <groupId>org.apache.velocity</groupId>
            <artifactId>velocity-engine-core</artifactId>
            <version>2.2</version>
        </dependency>

創建生成器類,然后執行main方法

package com.zys.mybatisplusdemo.config;

import com.baomidou.mybatisplus.core.toolkit.StringPool;
import com.baomidou.mybatisplus.generator.AutoGenerator;
import com.baomidou.mybatisplus.generator.InjectionConfig;
import com.baomidou.mybatisplus.generator.config.*;
import com.baomidou.mybatisplus.generator.config.po.TableInfo;
import com.baomidou.mybatisplus.generator.config.rules.NamingStrategy;
import com.baomidou.mybatisplus.generator.engine.FreemarkerTemplateEngine;

import java.util.ArrayList;
import java.util.List;

/**
 * @Aauthor yushizhong
 * @Date 2020/5/17 16:45
 * @Dec 代碼生成器
 */
public class CodeGenerator {

    public static void main(String[] args) {

        // 代碼生成器
        AutoGenerator map = new AutoGenerator();

        // 全局配置
        GlobalConfig globalConfig = new GlobalConfig();
        //配置生成文件的輸出目錄
        globalConfig.setOutputDir(System.getProperty("user.dir") + "/src/main/java");
        //設置開發人員名稱
        globalConfig.setAuthor("yushizhong");
        //是否打開輸出目錄
        globalConfig.setOpen(false);
        //mapper 命名方式
        globalConfig.setMapperName("%sDao");
        //service 命名方式
        globalConfig.setServiceName("%sService");
        map.setGlobalConfig(globalConfig);

        //數據源配置
        DataSourceConfig dataSourceConfig = new DataSourceConfig();
        //數據庫的路徑
        dataSourceConfig.setUrl("jdbc:mysql://localhost:3306/test?useUnicode=true&useSSL=false&characterEncoding=utf8&serverTimezone=CTT");
        //數據庫驅動名稱
        dataSourceConfig.setDriverName("com.mysql.jdbc.Driver");
        //數據庫的登錄用戶名
        dataSourceConfig.setUsername("root");
        //數據庫的登錄密碼
        dataSourceConfig.setPassword("123456");
        map.setDataSource(dataSourceConfig);

        // 包配置
        PackageConfig pc = new PackageConfig();
        //設置父包名
        pc.setParent("com.zys.mybatisplusdemo");
        pc.setMapper("dao");
        map.setPackageInfo(pc);

        // 自定義配置
        InjectionConfig cfg = new InjectionConfig() {
            @Override
            public void initMap() {
            }
        };
        String templatePath = "/templates/mapper.xml.vm";
        // 自定義輸出配置
        List<FileOutConfig> focList = new ArrayList<>();
        // 自定義配置會被優先輸出
        focList.add(new FileOutConfig(templatePath) {
            @Override
            public String outputFile(TableInfo tableInfo) {
                //設置xml的輸出路徑
                return System.getProperty("user.dir") + "/src/main/resources/mapper/" + tableInfo.getEntityName() + "Mapper" + StringPool.DOT_XML;
            }
        });
        cfg.setFileOutConfigList(focList);
        map.setCfg(cfg);

        // 配置模板
        TemplateConfig templateConfig = new TemplateConfig();
        //在代碼總不生成xml
        templateConfig.setXml(null);
        map.setTemplate(templateConfig);

        // 策略配置
        StrategyConfig strategy = new StrategyConfig();
        //數據庫表映射到實體的命名策略:把下划線變成大寫
        strategy.setNaming(NamingStrategy.underline_to_camel);
        //數據庫表字段映射到實體的命名策略:把下划線變成大寫
        strategy.setColumnNaming(NamingStrategy.underline_to_camel);
        //是否使用lombok
        strategy.setEntityLombokModel(true);
        strategy.setRestControllerStyle(true);
        // 寫於父類中的公共字段
        strategy.setSuperEntityColumns("id");
        strategy.setControllerMappingHyphenStyle(true);
        //表前綴
        strategy.setTablePrefix(pc.getModuleName() + "_");
        map.setStrategy(strategy);

        //執行
        map.execute();
    }


}

7.實現緩存

對於有些查詢比較頻繁的數據,可以放到緩存中,這里就以redis為例。mybatis-plus的緩存和mybatis的緩存實現原理類似,也有區別,mybatis的緩存實現請參考https://www.cnblogs.com/zys2019/p/11447169.html#_label7

7.1實戰演練

1)導入redis的依賴,配置redis數據庫參數(見源碼)

<dependency>
     <groupId>org.springframework.boot</groupId>
     <artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>

2)在配置文件中開啟緩存

mybatis-plus:
  configuration:
    #開啟緩存
    cache-enabled: true

如果不開啟,那么緩存就不會生效。

3)獲取spring創建的工廠

package com.zys.mybatisplusdemo.util;

import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.context.annotation.Configuration;

/**
 * @author zhongyushi
 * @date 2020/9/16 0016
 * @dec 獲取spring創建的工廠
 */
@Configuration
public class ApplicationContextUtil implements ApplicationContextAware {

    private static ApplicationContext applicationContext;

    //把非spring創建好的工廠賦值給applicationContext,applicationContext在這個應用中是唯一的
    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        this.applicationContext = applicationContext;
    }

    //此創建好工廠后再獲取對象
    public static Object getBean(String beanName){
        return applicationContext.getBean(beanName);
    }
}

4)創建redis緩存配置類,實現Cache,重寫方法

package com.zys.mybatisplusdemo.config;

import com.zys.mybatisplusdemo.util.ApplicationContextUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.cache.Cache;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.StringRedisSerializer;

import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;

/**
 * @author zhongyushi
 * @date 2020/9/28 0028
 * @dec MybatisPlus緩存配置,使用redis作為緩存服務器
 */
@Slf4j
public class MybatisPlusCache implements Cache {
    // 讀寫鎖
    private final ReadWriteLock readWriteLock = new ReentrantReadWriteLock(true);

    //這里使用了redis緩存,使用springboot自動注入
    private RedisTemplate<String, Object> redisTemplate;

    private String id;

    //是mybatis必須要求的,必寫。此id是xml中的namespace的值
    public MybatisPlusCache(final String id) {
        if (id == null) {
            throw new IllegalArgumentException("未獲取到緩存實例id");
        }
        this.id = id;
    }

    //返回cache的唯一名稱
    @Override
    public String getId() {
        return this.id;
    }

    //緩存存值
    @Override
    public void putObject(Object key, Object value) {
        //id是namespace的值,key是方法名,value是查詢的結果
        getRedisTemplate().opsForHash().put(id, key.toString(), value);
    }

    //緩存取值
    @Override
    public Object getObject(Object key) {
        return getRedisTemplate().opsForHash().get(id, key.toString());
    }

    //mybatis保留方法
    @Override
    public Object removeObject(Object key) {
        return null;
    }

    //清空緩存,在增刪改時會自動調用
    @Override
    public void clear() {
        getRedisTemplate().delete(id);
    }

    @Override
    public int getSize() {
        return getRedisTemplate().opsForHash().size(id).intValue();
    }

    @Override
    public ReadWriteLock getReadWriteLock() {
        return this.readWriteLock;
    }

    //獲取RedisTemplate,不能通過注入的方式,原因是此類是由mybatis實例化的
    private RedisTemplate getRedisTemplate() {
        //從上下文中獲取redisTemplate
        RedisTemplate redisTemplate = (RedisTemplate) ApplicationContextUtil.getBean("redisTemplate");
        //設置key是string類型的序列
        redisTemplate.setKeySerializer(new StringRedisSerializer());
        //設置hashKey是string類型的序列
        redisTemplate.setHashKeySerializer(new StringRedisSerializer());
        return redisTemplate;
    }
}

在這個類中,分別重寫了緩存設置、獲取和刪除的方法,把數據放到redis中。但是在此類中無法直接注入RedisTemplate,此類是由mybatis實例化的,不是由工廠實例化的。但是可以通過applicationContext來獲取。

4)開啟緩存

在UserDao接口上添加注解,指定緩存的配置類

@CacheNamespace(implementation= MybatisPlusCache.class,eviction=MybatisPlusCache.class)
public interface UserDao extends BaseMapper<User> {
    ...
}

5)測試。啟動項目,第一次訪問http://localhost:8080/users/list,查看控制台,會發現打印了sql的執行日志,多次訪問此路徑,它就從redis中獲取數據了,同時可以在redis中看到此緩存信息。

 對於增刪改操作,都會清空緩存。因此作為緩存的數據一般是頻繁查詢,很少修改的信息。

7.2注意事項

通過對比mybatis的緩存可以發現,這里指定緩存的配置類是在dao接口上用注解配置的,而mybatis是在xml中配置的。實際上,也可以在xml中配置,但是二者不可兼得。

1)在dao接口中配置,那么只能緩存使用mybatis-plus查詢出來的數據。也就是說,在xml中編寫的查詢語句所查詢的結果是不會存入緩存的。

2)在xml中配置,那么只能緩存xml中編寫的查詢語句所查詢的結果,使用mybatis-plus查詢出來的數據是不會存入緩存的。

xml中配置如下:

 <cache type="com.zys.mybatisplusdemo.config.MybatisPlusCache"/>

說明:使用mybatis-plus查詢出來的數據指的是不編寫sql,直接調用其內部已經編寫好的查詢方法。

8.@TableField注解詳細說明

8.1說明

屬性名 描述
value 映射數據庫的字段名
update 預處理set進行自定義注入(結合fill)
condition  預處理where進行自定義條件查詢(不常用)
exist 是否映射數據庫的字段(默認是true,值為false則不映射)
fill 字段填充,需結合FieldFill使用

 

對於value和exist在前面已經介紹,在此不再贅述。

8.2 update-修改時操作

1)注入當前的時間

假如在每次更新數據時都需要把時間改成當前操作的時間,那么可以對其進行配置為數據庫的時間:

@TableField(value = "update_time", update = "now()",fill = FieldFill.UPDATE)
private Date updateTime;

需要結合fill使用,將其設置為更新時更新數據。設置后需調用mybatisplus自帶的修改方法update(),否則不生效

輸入的SQL如下:

UPDATE 表 SET update_time=now() WHERE 條件

2)修改變量的值

在每次修改時需要記錄修改次數時,可以使用下面的方式。

@TableField(value = "count",update = "%s+1", fill = FieldFill.UPDATE)
private Integer count;

其中"%s"是填充的字段,在這里是count,輸出的SQL如下:

UPDATE 表 SET count=count+1 WHERE 條件

不過需要注意的是,在使用時,count在數據庫中必須有值,為空時不會修改其值。

8.3 fill與FieldFill

對數據進行自動填充操作。上一小節結合update屬性進行了說明。本小節不結合update屬性進行添加或修改。

若需要在添加時插入添加時間,修改時同步修改時間。可對對象的字段進行設置,使用fill:

@TableField(value = "create_time", fill = FieldFill.INSERT)
private Date createTime;

@TableField(value = "update_time", fill = FieldFill.UPDATE)
private Date updateTime;

還需要添加一個配置類實現MetaObjectHandler接口,重寫兩個方法

import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.context.annotation.Configuration;

import java.util.Date;

@Configuration
public class MyMetaObjectHandler implements MetaObjectHandler {

    @Override
    public void insertFill(MetaObject metaObject) {
        this.setFieldValByName("createTime", new Date(), metaObject);
    }

    @Override
    public void updateFill(MetaObject metaObject) {
        this.setFieldValByName("updateTime", new Date(), metaObject);
    }
}

可以看出在配置類中對方法重寫時,指定了字段名和時間,從而實現自定義插入時間。其他的公共字段也可以使用這種方式。

這種方式顯而易見有很大的局限性,對時間的兩個字段進行了限定,那么對象的這兩個字段就固定了。可根據實際需求選擇是否使用這種方式。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM