首页 > 其他分享 >Mybatis-Plus 常用注解总结

Mybatis-Plus 常用注解总结

时间:2023-12-28 23:24:17浏览次数:19  
标签:String default private Plus import Mybatis 注解 com public

在框架的使用中,注解约定大于配置,我们可以轻松通过注解完成很多工作,比如字段改名映射,插入更新的时间写入等,下面的学习内容主要列举了常用的注解。

我们看看官网中列出的注解有哪些[1]:

image.png

本文的注解学习主要内容集中在以下的注解中:

  • @TableName
  • @TableId
  • @TableField
  • @EnumValue
  • @Version
  • @TableLogic

环境:

  • Mybatis-Plus: 3.5.5

@TableName

先看看源码:

@Documented
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.TYPE, ElementType.ANNOTATION_TYPE})
public @interface TableName {
    String value() default "";

    String schema() default "";

    boolean keepGlobalPrefix() default false;

    String resultMap() default "";

    boolean autoResultMap() default false;

    String[] excludeProperty() default {};
}

开放的功能很多,我们平时可能并用不到,主要需要注意的是 value , 我们通过设置 value = "table_xxx" ,注解加在实体类上,映射实体类和数据库表的表名。

@TableId

源码:

@Documented
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.FIELD, ElementType.ANNOTATION_TYPE})
public @interface TableId {
    String value() default "";

    IdType type() default IdType.NONE;
}

注解字段的,通过设置 value 声明在数据库表的字段名,通过 type 属性声明用哪种类型的命名策略,常见的策略有:

image.png

比如我们常用的自增主键,或者通过指定id,默认使用微博开源的雪花算法生成id,全局唯一且自增id,即:

  • @TableId(type = IdType.AUTO)
  • @TableId(type = IdType.ASSIGN_ID)

@TableField

源码:

@Documented
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.FIELD, ElementType.ANNOTATION_TYPE})
public @interface TableField {
    String value() default "";

    boolean exist() default true;

    String condition() default "";

    String update() default "";

    FieldStrategy insertStrategy() default FieldStrategy.DEFAULT;

    FieldStrategy updateStrategy() default FieldStrategy.DEFAULT;

    FieldStrategy whereStrategy() default FieldStrategy.DEFAULT;

    FieldFill fill() default FieldFill.DEFAULT;

    boolean select() default true;

    boolean keepGlobalFormat() default false;

    String property() default "";

    JdbcType jdbcType() default JdbcType.UNDEFINED;

    Class<? extends TypeHandler> typeHandler() default UnknownTypeHandler.class;

    boolean javaType() default false;

    String numericScale() default "";
}

该注解提供的功能很多,这里讲几个常用的。

value

通过设置该值,对应到数据库表的字段名。

condition

设定值,进而是否开启如模糊查询。

exist

主要指明字段在不在数据库表中,如果 false 则不在数据库表中。

select

注明查到的字段是否要出现在返回结果中,某些场景中,如 User 表中,可能有 password ,对于这种敏感的字段,是不是可以不用返回呢。

fill

这里涉及自动填充,在哪些场景中会用到呢,如 插入、更新、更改的时间,我们希望自动填入,其原理其实也是通过设置实体的值,进而达到自动填入的功能。

填入时机:

image.png

如果设置了该 fill 属性,则我们需要去实现或者继承 MetaObjectHandler 接口:

package com.example.springbootmybatisplusdemo.config;

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

import java.time.LocalDateTime;

@Configuration
@MapperScan(basePackages = "com.example.springbootmybatisplusdemo.mapper")
public class AutoTimeConfig implements MetaObjectHandler {
    @Override
    public void insertFill(MetaObject metaObject) {
        // method 1
        this.strictInsertFill(metaObject, "created", () -> LocalDateTime.now(), LocalDateTime.class);
        this.strictInsertFill(metaObject, "modified", () -> LocalDateTime.now(), LocalDateTime.class);
        // method 2
        // setFieldValByName("created", LocalDateTime.now(), metaObject);
    }

    @Override
    public void updateFill(MetaObject metaObject) {
        this.strictUpdateFill(metaObject, "updated", () -> LocalDateTime.now(), LocalDateTime.class);
    }
}

在上面的实现中,我们实现了 insertFill/updateFill 两个方法,另外对于字段值的填充,在代码中也注明了2种方法。

@EnumValue

源码:

@Documented
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.FIELD, ElementType.ANNOTATION_TYPE})
public @interface EnumValue {
}

这里的使用上,我们需要加到会在数据库表中显示的字段上,比如我们的实体类:

private GenderEnum gender;

GenderEnum 是一个枚举类:

package com.example.springbootmybatisplusdemo.entity;

import com.baomidou.mybatisplus.annotation.EnumValue;

public enum GenderEnum {
    Male(1, "Male"),
    Female(0, "Female");

    @EnumValue
    private final int code;

    private final String desc;

    GenderEnum(int code, String desc) {
        this.code = code;
        this.desc = desc;
    }
}

通过上述的配置,我们就可以在设置 gender 字段时,通过 GenderEnum 枚举类给定 Male或者Female,最后写入数据库表时,实际是写入的 code 的值,注意我们声明的 1 -> Male,0 -> Female,所以在数据库表中,gender 实际填入的值是 0/1

@Value

该注解主要用于乐观锁,结合拦截件使用:

package com.example.springbootmybatisplusdemo.config;

import com.baomidou.mybatisplus.extension.plugins.MybatisPlusInterceptor;
import com.baomidou.mybatisplus.extension.plugins.inner.OptimisticLockerInnerInterceptor;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.transaction.annotation.EnableTransactionManagement;

@Configuration
@EnableTransactionManagement
@MapperScan(basePackages = "com.example.springbootmybatisplusdemo.mapper")
public class MybatisPlusConfig {
    // register 乐观锁插件
    @Bean
    public MybatisPlusInterceptor mybatisPlusInterceptor() {
        MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();
        interceptor.addInnerInterceptor(new OptimisticLockerInnerInterceptor());
        return interceptor;
    }
}

测试:

package com.example.springbootmybatisplusdemo.test;

import com.example.springbootmybatisplusdemo.entity.UserDemo;
import com.example.springbootmybatisplusdemo.mapper.UserDemoMapper;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;

@SpringBootTest
public class optimisticLockTest {
    @Autowired
    private UserDemoMapper userMapper;

    @Test
    public void lockTest() {
        UserDemo user1 = new UserDemo();
        user1.setId(100L);
        user1.setVersion(1);
        UserDemo user2 = new UserDemo();
        user2.setId(100L);
        user2.setVersion(1);
        userMapper.updateById(user1); // ok
        userMapper.updateById(user2); // fail
    }
}

@TableLogic

该注解用于逻辑删除,真删除是删除数据库表中的记录行,逻辑删除则是标记某个字段的值,如:

@TableLogic(value = "0", delval = "1") 
private Integer deleted;

其中 value 是原值,delval 是删除后填入的值,如删除前,deleted为0,删除后deleted为1,我们在查询数据时注意下这个字段即可。

demo

以下是以上注解在 case 中的使用:

package com.example.springbootmybatisplusdemo.entity;

import com.baomidou.mybatisplus.annotation.*;
import lombok.Data;

import java.time.LocalDateTime;

@Data
@TableName(value = "user_demo") // tableName
public class UserDemo {
    @TableId(type = IdType.AUTO) // tableId,自增类型,主键
    private Long id;

    @TableId(type = IdType.ASSIGN_ID) // 该策略使用接口IdentifierGenerator的方法nextId(以实现类为DefaultIdentifierGenerator雪花算法)
    private Long myId;

    @TableField(value = "name", condition = SqlCondition.LIKE) // tableField,开启模糊查询
    private String username;

    @TableField(exist = false) // 指明字段不在数据表中
    private String username1;

    @TableField(select = false) // 字段不出现在返回结果中
    private String password;

    @TableField(fill = FieldFill.INSERT) // 如果继承接口,已经实现了insertFill,需要实现 MetaObjectHandler,见AutoTimeConfig
    private LocalDateTime created;

    @TableField(fill = FieldFill.UPDATE) // 需要实现 MetaObjectHandler
    private LocalDateTime updated;

    @TableField(fill = FieldFill.INSERT_UPDATE) // 需要实现 MetaObjectHandler
    private LocalDateTime modified;

    private GenderEnum gender; // enumValue

    @Version
    private Integer version; // version,乐观锁,集合配置使用,如拦截件

    @TableLogic(value = "0", delval = "1") // 逻辑删除,其实就是更新delete字段的值,0 -> 1, update table_name set deleted=1 where xxx=yyy, or delete from table_name where xxx=yyy
    private Integer deleted;
}

参考:

标签:String,default,private,Plus,import,Mybatis,注解,com,public
From: https://www.cnblogs.com/davis12/p/17933803.html

相关文章

  • Java Spring Boot Mybatis-Plus 的简单使用
    此文主要基于官网case整理,如需了解更多详情,请移步官网。环境:SpringBoot:3.1.6JDK:17MySQL:5.7数据准备主要是MySQL建库建表,插入一些数据。建库:CREATEDATABASEmybatis_demo;建表:DROPTABLEIFEXISTS`user`;CREATETABLE`user`(idBIGINTNOTNULLCOMME......
  • 【转载】 @configuration注解详解
    为了能深入地掌握SpringBoot的自动配置原理,我们来看一下SpringBoot的一些底层注解,要知道它们是如何完成相关功能的。首先,我们来看一下怎么给容器里面添加组件。我在这儿准备了两个组件,它们分别是:用户,即User类packagecom.spring.learn.bean;publicclassUser{privat......
  • D. Split Plus K
    原题链接什么时候无解?有解计算code#include<bits/stdc++.h>#definelllonglongusingnamespacestd;lla[200005]={0};intmain(){llt;cin>>t;while(t--){lln,k;cin>>n>>k;llzs=0,fs=0;f......
  • java注解
    一、注解概述 二、JDK内置注解1、@Override 2、@Deprecated 3、@SuppressWarnings 4、@Functionalinterface 三、元注解1、概念 2、@Retention 3、@Target 四、自定义注解  五、注解的注意事项  六、通过注解运行指定类中的指......
  • Wpf 通过数据注解(特性)校验表单+Prism8+IDataErrorInfo
    十年河东,十年河西,莫欺少年穷学无止境,精益求精参考:WPF表单验证摘要WPF表单验证是WPF重要基础设施之一,依靠MVVM的数据绑定机制及微软的有力封装,使得我们在处理实体表单验证等可以快捷高效的灵活处理。常见的表单验证实现大概有Exception 、ValidationRule 、IDataErrorInfo ,......
  • 【SpringBoot快速入门】(3)SpringBoot整合junit和MyBatis 详细代码示例与讲解
    目录1.SpringBoot整合junit1.1环境准备1.2编写测试类2.SpringBoot整合mybatis2.1回顾Spring整合Mybatis2.2SpringBoot整合mybatis2.2.1创建模块2.2.2定义实体类2.2.3定义dao接口2.2.4定义测试类2.2.5编写配置2.2.6测试2.2.7使用Druid数据源之前我们已经学习的Spring、......
  • 【Spring教程31】SSM框架整合实战:从零开始学习SSM整合配置,如何编写Mybatis SpringMVC
    目录1流程分析2整合配置2.1步骤1:创建Maven的web项目2.2步骤2:添加依赖2.3步骤3:创建项目包结构2.4步骤4:创建SpringConfig配置类2.5步骤5:创建JdbcConfig配置类2.6步骤6:创建MybatisConfig配置类2.7步骤7:创建jdbc.properties2.8步骤8:创建SpringMVC配置类2.9步骤9:创......
  • lombok 常用注解图文详解(含代码)
    文章目录1.@Getter/@Setter1.1可用于成员变量上1.1.1可选择生成方法的修饰符1.2可用于类上1.2.1静态变量不会生成相应方法1.2.2常量不会生成Setter方法1.2.3单独设置某个变量不可查看(同1.1)[email protected]排除某些成员变量2.2输出指定变量[email protected]生......
  • 「快速上手」Lombok常用注解大全
    Lombok注解教学Lombok是一个Java库,它通过注解的方式来简化Java代码的编写,减少样板代码(boilerplatecode)的重复,提高代码的可读性和可维护性。本文将介绍Lombok库中常用的注解及其用法。1.@Getter和@Setter@Getter和@Setter是Lombok中最常用的注解之一,它们用于自动生成JavaBe......
  • Jackson注解大全(上)
    Jackson是当前用的比较广泛的,用来序列化和反序列化json的Java开源框架。Jackson社区相对比较活跃,更新速度也比较快,从Github中的统计来看,Jackson是最流行的json解析器之一,SpringMVC、SprigBoot的默认json解析器都是Jackson。Jackson优点很多:Jackson所依赖的jar包较少,简单易......