The difference between Mybatis-Plus and Mybatis

​​​​​​

difference one

If Mybatis Plus is a wrench, then Mybatis Generator is a factory that produces wrenches.

In layman's terms——

MyBatis: A framework for operating databases. It provides a Mapper class that supports database operations that allow you to add, delete, modify, and query with java code, saving you the trouble of handwriting sql statements every time . but! There is a premise, you have to write the sql statement in xml first, is it very troublesome? So there is the following ↓

Mybatis Generator: A tool that automatically generates simple sql statements for Mybatis , saving a lot of time. When the two are used together, the development speed is so fast. As the title says↓

Mybatis Plus: The framework developed by the Chinese team Baomidou on the basis of Mybatis, has expanded many functions on the basis of Mybatis, and won the fifth place in the most popular domestic open source software in 2018. Of course, there are supporting packages↓

Mybatis Plus Generator: also developed for Baomidou, more powerful than Mybatis Generator, supports more functions, and automatically generates Entity, Mapper, Service, Controller, etc.

Summarize:

Database framework: Mybatis Plus > Mybatis

Code generator: Mybatis Plus Generator > Mybatis Generator

difference two

Mybatis-Plus is a Mybatis enhancement tool that enhances Mybatis without changing it. After using Mybatis-Plus, we can use both the unique functions of Mybatis-Plus and the native functions of Mybatis. Mybatis-Plus (hereinafter referred to as MP) was born to simplify development and improve development efficiency, but it also provides some interesting plug-ins, such as SQL performance monitoring, optimistic locking, execution analysis, etc.

Although Mybatis has provided us with great convenience, it still has shortcomings. In fact, nothing is perfect. The existence of MP is to make up for the shortcomings of Mybatis. When we use Mybatis, we will find that whenever we want to write a business logic, we must write a method in the DAO layer, and then correspond to a SQL. Even if it is a simple conditional query, even if only one condition is changed, it must be updated in the DAO layer. Add a method. For this problem, MP provides a good solution, which I will introduce later. In addition, MP's code generator is also a very interesting thing, it allows us to avoid a lot of repetitive work, I will introduce how to integrate MP in your project below.

1.  Integration steps ↓: (First, you need a spring project)

Integrate dependencies, just add dependencies to pom, not much to say:

<!-- mybatis mybatis-plus mybatis-spring mvc -->  
<dependency>  
    <groupId>com.baomidou</groupId>  
    <artifactId>mybatis-plus</artifactId>  
    <version>${mybatis-plus.version}</version>  
</dependency>  
<dependency>  
    <groupId>org.apache.velocity</groupId>  
    <artifactId>velocity-engine-core</artifactId>  
    <version>2.0</version>  
</dependency>  

Note: The version used by the author is: mybatis-plus.version=2.1-gamma, there are two dependencies in the above code, the first is the core dependency of mybatis-plus, and the second is the template engine required when using the code generator Dependency, if you don't plan to use the code generator, you don't need to import it here.

Note: Mybatis and mybatis-spring have been integrated in the core jar package of mybatis-plus, so to avoid conflicts, please do not refer to these two jar packages again.

Second, configure MP in spring:

<bean id="sqlSessionFactory"  
    class="com.baomidou.mybatisplus.spring.MybatisSqlSessionFactoryBean">  
    <!-- 配置数据源 -->  
    <property name="dataSource" ref="dataSource" />  
    <!-- 自动扫描 Xml 文件位置 -->  
    <property name="mapperLocations" value="classpath*:com/ds/orm/mapper/**/*.xml" />  
    <!-- 配置 Mybatis 配置文件(可无) -->  
    <property name="configLocation" value="classpath:mybatis-config.xml" />  
    <!-- 配置包别名,支持通配符 * 或者 ; 分割 -->  
    <property name="typeAliasesPackage" value="com.ds.orm.model" />  
    <!-- 枚举属性配置扫描,支持通配符 * 或者 ; 分割 -->  
    <!-- <property name="typeEnumsPackage" value="com.baomidou.springmvc.entity.*.enums"   
        /> -->  
    <!-- 以上配置和传统 Mybatis 一致 -->  
  
    <!-- MP 全局配置注入 -->  
    <property name="globalConfig" ref="globalConfig" />  
</bean>  

<bean id="globalConfig" class="com.baomidou.mybatisplus.entity.GlobalConfiguration">  
    <!-- 主键策略配置 -->  
    <!-- 可选参数 AUTO->`0`("数据库ID自增") INPUT->`1`(用户输入ID") ID_WORKER->`2`("全局唯一ID")   
        UUID->`3`("全局唯一ID") -->  
    <property name="idType" value="2" />  
    <!-- 数据库类型配置 -->  
    <!-- 可选参数(默认mysql) MYSQL->`mysql` ORACLE->`oracle` DB2->`db2` H2->`h2`   
        HSQL->`hsql` SQLITE->`sqlite` POSTGRE->`postgresql` SQLSERVER2005->`sqlserver2005`   
        SQLSERVER->`sqlserver` -->  
    <property name="dbType" value="mysql" />  
    <!-- 全局表为下划线命名设置 true -->  
    <property name="dbColumnUnderline" value="true" />  
    <property name="sqlInjector">  
        <bean class="com.baomidou.mybatisplus.mapper.AutoSqlInjector" />  
    </property>  
</bean>  
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">  
    <description>DAO接口所在包名,Spring会自动查找其下的类</description>  
    <property name="basePackage" value="com.ds.orm.mapper" />  
    <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory" />  
</bean>  
<!-- 乐观锁插件 -->  
<bean class="com.baomidou.mybatisplus.plugins.OptimisticLockerInterceptor" />  
  
<!-- xml mapper热加载 sqlSessionFactory:session工厂 mapperLocations:mapper匹配路径   
    enabled:是否开启动态加载 默认:false delaySeconds:项目启动延迟加载时间 单位:秒 默认:10s sleepSeconds:刷新时间间隔   
    单位:秒 默认:20s -->  
<bean class="com.baomidou.mybatisplus.spring.MybatisMapperRefresh">  
    <constructor-arg name="sqlSessionFactory" ref="sqlSessionFactory" />  
    <constructor-arg name="mapperLocations"  
        value="classpath*:com/ds/orm/mapper/*/*.xml" />  
    <constructor-arg name="delaySeconds" value="10" />  
    <constructor-arg name="sleepSeconds" value="20" />  
    <constructor-arg name="enabled" value="true" />  
</bean>  
  
<!-- 事务 -->  
<bean id="transactionManager"  
    class="org.springframework.jdbc.datasource.DataSourceTransactionManager">  
    <property name="dataSource" ref="dataSource" />  
</bean>  
<tx:annotation-driven transaction-manager="transactionManager"  
    proxy-target-class="true" />  
    
 注意:只要做如上配置就可以正常使用mybatis了,不要重复配置。MP的配置和mybatis一样,都是配置一个sqlSessionFactory,只是现在所配置的类在原本的SqlSessionFactoryBean基础上做了增强。插件等配置请按需取舍。
插件配置,按需求配置就可以,此处把可以配置的插件都列了出来,具体的请看代码注释:

<configuration>  
    <settings>  
        <setting name="logImpl" value="SLF4J" />  
        <!-- 字段为空时仍调用model的set方法或map的put方法 -->  
        <setting name="callSettersOnNulls" value="true" />  
    </settings>  
    <plugins>  
        <!-- | 分页插件配置 | 插件提供二种方言选择:1、默认方言 2、自定义方言实现类,两者均未配置则抛出异常! | overflowCurrent   
            溢出总页数,设置第一页 默认false | optimizeType Count优化方式 ( 版本 2.0.9 改为使用 jsqlparser 不需要配置   
            ) | -->  
        <!-- 注意!! 如果要支持二级缓存分页使用类 CachePaginationInterceptor 默认、建议如下!! -->  
        <plugin interceptor="com.baomidou.mybatisplus.plugins.PaginationInterceptor">  
            <property name="dialectType" value="mysql" />  
            <!--<property name="sqlParser" ref="自定义解析类、可以没有" />  
            <property name="localPage" value="默认 false 改为 true 开启了 pageHeper 支持、可以没有" />  
            <property name="dialectClazz" value="自定义方言类、可以没有" /> -->  
        </plugin>  
  
        <!-- SQL 执行性能分析,开发环境使用,线上不推荐。 maxTime 指的是 sql 最大执行时长 -->  
        <plugin interceptor="com.baomidou.mybatisplus.plugins.PerformanceInterceptor">  
            <property name="maxTime" value="2000" />  
            <!--SQL是否格式化 默认false -->  
            <property name="format" value="true" />  
        </plugin>  
  
        <!-- SQL 执行分析拦截器 stopProceed 发现全表执行 delete update 是否停止运行 该插件只用于开发环境,不建议生产环境使用。。。 -->  
        <plugin interceptor="com.baomidou.mybatisplus.plugins.SqlExplainInterceptor">  
            <property name="stopProceed" value="false" />  
        </plugin>  
    </plugins>  
</configuration>  

Note: The execution analysis interceptor and performance analysis are recommended only for debugging programs during development. In order to ensure program performance and stability, it is recommended to comment out these two plug-ins in the production environment.

Data source: (druid is used here)

<!-- 配置数据源 -->  
<bean name="dataSource" class="com.alibaba.druid.pool.DruidDataSource" init-method="init" destroy-method="close">  
    <!--     <property name="driverClassName" value="${jdbc.driverClassName}" /> -->  
    <property name="url" value="${jdbc.url}" />   
    <property name="username" value="${jdbc.username}" />   
    <property name="password" value="${jdbc.password}" />   
    <property name="initialSize" value="${jdbc.initialSize}" />   
    <property name="minIdle" value="${jdbc.minIdle}" />   
    <property name="maxActive" value="${jdbc.maxActive}" />   
    <property name="maxWait" value="${jdbc.maxWait}" />   
    <property name="timeBetweenEvictionRunsMillis" value="${jdbc.timeBetweenEvictionRunsMillis}" />   
    <property name="minEvictableIdleTimeMillis" value="${jdbc.minEvictableIdleTimeMillis}" />   
    <property name="validationQuery" value="${jdbc.validationQuery}" />   
    <property name="testWhileIdle" value="${jdbc.testWhileIdle}" />   
    <property name="testOnBorrow" value="${jdbc.testOnBorrow}" />   
    <property name="testOnReturn" value="${jdbc.testOnReturn}" />   
    <property name="removeAbandoned" value="${jdbc.removeAbandoned}" />   
    <property name="removeAbandonedTimeout" value="${jdbc.removeAbandonedTimeout}" />   
    <!--     <property name="logAbandoned" value="${jdbc.logAbandoned}" /> -->  
    <property name="filters" value="${jdbc.filters}" />  
    <!-- 关闭abanded连接时输出错误日志 -->  
    <property name="logAbandoned" value="true" />  
    <property name="proxyFilters">  
        <list>  
            <ref bean="log-filter"/>  
        </list>  
    </property>  
  
    <!-- 监控数据库 -->  
    <!-- <property name="filters" value="stat" /> -->  
    <!--     <property name="filters" value="mergeStat" />-->  
</bean>  

At this point, MP has been integrated into our project, and the following will introduce how it simplifies our development

3. Simple CURD operation ↓:

Assuming that we have a user table and have created an entity class User corresponding to this table, let's introduce the simple addition, deletion, modification and query operations of users.

Create a DAO layer interface. When we use ordinary mybatis, we will create a DAO layer interface and correspond to an xml for writing SQL. Here we also need to create a DAO layer interface, but if it is not necessary, we don’t even need to create xml to perform CURD operations on resources. We only need to let our established DAO inherit the BaseMapper<?> provided by MP :

public interface UserMapper extends BaseMapper { }

//然后在我们需要做数据CURD时,像下边这样就好了:

// 初始化 影响行数
int result = 0;
// 初始化 User 对象
User user = new User();

// 插入 User (插入成功会自动回写主键到实体类)
user.setName(“Tom”);
result = userMapper.insert(user);

// 更新 User
user.setAge(18);
result = userMapper.updateById(user);//user要设置id哦,具体的在下边我会详细介绍

// 查询 User
User exampleUser = userMapper.selectById(user.getId());

// 查询姓名为‘张三’的所有用户记录
List userList = userMapper.selectList(
new EntityWrapper().eq(“name”, “张三”)
);

// 删除 User
result = userMapper.deleteById(user.getId());

Is it convenient? If you only use mybatis, you need to write 4 SQL and 4 methods. Of course, the above methods alone are far from meeting our needs. Please read below:

Multi-condition pagination query:

// Query 10 user records whose name is 'Zhang San', gender is male, and age is between 18 and 50

List<User> userList = userMapper.selectPage(  
        new Page<User>(1, 10),  
        new EntityWrapper<User>().eq("name", "张三")  
                .eq("sex", 0)  
                .between("age", "18", "50")  
);  

/**Equivalent to SELECT *
*FROM sys_user
*WHERE (name='Zhang San' AND sex=0 AND age BETWEEN '18' AND '50')
*LIMIT 0,10
*/

Below this, the multi-condition constructor. In fact, for queries with too complicated conditions, the author still recommends using the native mybatis method, which is easy to maintain and has clear logic. If all data operations are forced to use MP, the meaning of MP to simplify development will be lost. So please choose according to the actual situation when using it, let me introduce it here first.

public Page<T> selectPage(Page<T> page, EntityWrapper<T> entityWrapper) {  
  if (null != entityWrapper) {  
      entityWrapper.orderBy(page.getOrderByField(), page.isAsc());//排序  
  }  
  page.setRecords(baseMapper.selectPage(page, entityWrapper));//将查询结果放入page中  
  return page;  
}  

** Conditional construction one (entityWrapper parameter of the above method): **

public void testTSQL11() {  
    /* 
     * 实体带查询使用方法  输出看结果 
     */  
    EntityWrapper<User> ew = new EntityWrapper<User>();  
    ew.setEntity(new User(1));  
    ew.where("user_name={0}", "'zhangsan'").and("id=1")  
            .orNew("user_status={0}", "0").or("status=1")  
            .notLike("user_nickname", "notvalue")  
            .andNew("new=xx").like("hhh", "ddd")  
            .andNew("pwd=11").isNotNull("n1,n2").isNull("n3")  
            .groupBy("x1").groupBy("x2,x3")  
            .having("x1=11").having("x3=433")  
            .orderBy("dd").orderBy("d1,d2");  
    System.out.println(ew.getSqlSegment());  
}  

** Conditional construction two (same as above):**

int buyCount = selectCount(Condition.create()
.setSqlSelect(“sum(quantity)”)
.isNull(“order_id”)
.eq(“user_id”, 1)
.eq(“type”, 1)
.in(“status”, new Integer[]{0, 1})
.eq(“product_id”, 1)
.between(“created_time”, startDate, currentDate)
.eq(“weal”, 1));
自定义条件使用entityWrapper:

List selectMyPage(RowBounds rowBounds, @Param(“ew”) Wrapper wrapper);

SELECT * FROM user ${ew.sqlSegment} *Note: Don't worry about SQL injection here, MP has done string escape processing for ew. In fact, when using MP for data CURD, there is another method, AR (ActiveRecord), which is very simple. Let our entity class inherit MP to provide Model<?>, which may be different from our commonly used method. Let me briefly describe it below:*

// Entity class
@TableName("sys_user") // Annotation specifies the table name
public class User extends Model {

… // fields

… // getter and setter

.
.

/  Specify the primary key  / *
@Override
protected Serializable pkVal() { //Be sure to specify the primary key
return this.id;
}
}
.
.
.
The following is the CURD operation:

// Initialization success flag
boolean result = false;
// Initialization User
User user = new User();

// 保存 User
user.setName(“Tom”);
result = user.insert();

// Update User
user.setAge(18);
result = user.updateById();

// Query User
User exampleUser = t1.selectById();

// Query all user records whose name is 'Zhang San'
List userList1 = user.selectList(
new EntityWrapper().eq("name", "Zhang San")
);

// Delete User
result = t2.deleteById();

// Query 10 user records named 'Zhang San', male, and aged between 18 and 50 by pagination
List userList = user.selectPage(
new Page(1, 10),
new EntityWrapper().eq( "name", "Zhang San")
.eq("sex", 0)
.between("age", "18", "50")
).getRecords();

That's it. You may say that MP encapsulation is a bit too much. Doing so will disperse the data logic to different levels, which is difficult to manage and makes the code difficult to understand. In fact, this is indeed the case, which requires you to pay attention when using it. While simplifying development, you must also ensure that your code level is clear, make a strategic design or make a trade-off and balance

In fact, the functions introduced above are not all of MP. Let me introduce the most interesting module of MP - the code generator.

**

Step ↓:

As mentioned above, using the code generator must introduce the dependency of velocity-engine-core (template engine).

Preparation:

Selecting the primary key strategy is the configuration in which I introduced the MP configuration at the beginning of the above. If you don’t remember it, please scroll up! MP provides the following primary key strategies:

value description

IdType.AUTO ---------- Database ID auto-increment

IdType.INPUT ---------- user input ID

IdType.ID_WORKER---------- Globally unique ID, the content is empty and automatically filled (default configuration)

IdType.UUID ---------- Globally unique ID, if the content is empty, it will be automatically filled

MP uses ID_WORKER by default, which is partly optimized by MP on the basis of Sequence to generate a globally unique ID.

Table and field naming strategy selection, as above, is still in that configuration. The following paragraph is copied to the official MP document:

In MP, we recommend that database table names use underscore naming, while table field names use camel case naming.

The reason for this is to avoid performance loss when corresponding to entity classes, so that fields can directly correspond to entity classes without mapping. Of course, if you don’t need to consider this performance loss in the project, then it’s okay for you to use the underline. You only need to configure the dbColumnUnderline property when generating the code.

Create a table (the naming rules are based on what you configured just now, which will affect whether the class name and field name of the generated code are correct).
Execute the main method below to generate code:

import java.util.HashMap;  
import java.util.Map;  
  
import com.baomidou.mybatisplus.generator.AutoGenerator;  
import com.baomidou.mybatisplus.generator.InjectionConfig;  
import com.baomidou.mybatisplus.generator.config.DataSourceConfig;  
import com.baomidou.mybatisplus.generator.config.GlobalConfig;  
import com.baomidou.mybatisplus.generator.config.PackageConfig;  
import com.baomidou.mybatisplus.generator.config.StrategyConfig;  
import com.baomidou.mybatisplus.generator.config.rules.DbType;  
import com.baomidou.mybatisplus.generator.config.rules.NamingStrategy;  
  
/** 
 * <p> 
 * 代码生成器演示 
 * </p> 
 */  
public class MpGenerator {  
  
    /** 
     * <p> 
     * MySQL 生成演示 
     * </p> 
     */  
    public static void main(String[] args) {  
        AutoGenerator mpg = new AutoGenerator();  
  
        // 全局配置  
        GlobalConfig gc = new GlobalConfig();  
        gc.setOutputDir("D://");  
        gc.setFileOverride(true);  
        gc.setActiveRecord(true);// 不需要ActiveRecord特性的请改为false  
        gc.setEnableCache(false);// XML 二级缓存  
        gc.setBaseResultMap(true);// XML ResultMap  
        gc.setBaseColumnList(false);// XML columList  
    // .setKotlin(true) 是否生成 kotlin 代码  
        gc.setAuthor("Yanghu");  
  
        // 自定义文件命名,注意 %s 会自动填充表实体属性!  
        // gc.setMapperName("%sDao");  
        // gc.setXmlName("%sDao");  
        // gc.setServiceName("MP%sService");  
        // gc.setServiceImplName("%sServiceDiy");  
        // gc.setControllerName("%sAction");  
        mpg.setGlobalConfig(gc);  
  
        // 数据源配置  
        DataSourceConfig dsc = new DataSourceConfig();  
        dsc.setDbType(DbType.MYSQL);  
        dsc.setTypeConvert(new MySqlTypeConvert(){  
            // 自定义数据库表字段类型转换【可选】  
            @Override  
            public DbColumnType processTypeConvert(String fieldType) {  
                System.out.println("转换类型:" + fieldType);  
        // 注意!!processTypeConvert 存在默认类型转换,如果不是你要的效果请自定义返回、非如下直接返回。  
                return super.processTypeConvert(fieldType);  
            }  
        });  
        dsc.setDriverName("com.mysql.jdbc.Driver");  
        dsc.setUsername("root");  
        dsc.setPassword("521");  
        dsc.setUrl("jdbc:mysql://127.0.0.1:3306/mybatis-plus?characterEncoding=utf8");  
        mpg.setDataSource(dsc);  
  
        // 策略配置  
        StrategyConfig strategy = new StrategyConfig();  
    // strategy.setCapitalMode(true);// 全局大写命名 ORACLE 注意  
        strategy.setTablePrefix(new String[] { "tlog_", "tsys_" });// 此处可以修改为您的表前缀  
        strategy.setNaming(NamingStrategy.underline_to_camel);// 表名生成策略  
        // strategy.setInclude(new String[] { "user" }); // 需要生成的表  
        // strategy.setExclude(new String[]{"test"}); // 排除生成的表  
        // 自定义实体父类  
        // strategy.setSuperEntityClass("com.baomidou.demo.TestEntity");  
        // 自定义实体,公共字段  
        // strategy.setSuperEntityColumns(new String[] { "test_id", "age" });  
        // 自定义 mapper 父类  
        // strategy.setSuperMapperClass("com.baomidou.demo.TestMapper");  
        // 自定义 service 父类  
        // strategy.setSuperServiceClass("com.baomidou.demo.TestService");  
        // 自定义 service 实现类父类  
        // strategy.setSuperServiceImplClass("com.baomidou.demo.TestServiceImpl");  
        // 自定义 controller 父类  
        // strategy.setSuperControllerClass("com.baomidou.demo.TestController");  
        // 【实体】是否生成字段常量(默认 false)  
        // public static final String ID = "test_id";  
        // strategy.setEntityColumnConstant(true);  
        // 【实体】是否为构建者模型(默认 false)  
        // public User setName(String name) {this.name = name; return this;}  
        // strategy.setEntityBuilderModel(true);  
        mpg.setStrategy(strategy);  
  
        // 包配置  
        PackageConfig pc = new PackageConfig();  
        pc.setParent("com.baomidou");  
        pc.setModuleName("test");  
        mpg.setPackageInfo(pc);  
  
        // 注入自定义配置,可以在 VM 中使用 cfg.abc 【可无】  
        InjectionConfig cfg = new InjectionConfig() {  
            @Override  
            public void initMap() {  
                Map<String, Object> map = new HashMap<String, Object>();  
                map.put("abc", this.getConfig().getGlobalConfig().getAuthor() + "-mp");  
                this.setMap(map);  
            }  
        };  
  
        // 自定义 xxList.jsp 生成  
        List<FileOutConfig> focList = new ArrayList<FileOutConfig>();  
        focList.add(new FileOutConfig("/template/list.jsp.vm") {  
            @Override  
            public String outputFile(TableInfo tableInfo) {  
                // 自定义输入文件名称  
                return "D://my_" + tableInfo.getEntityName() + ".jsp";  
            }  
        });  
        cfg.setFileOutConfigList(focList);  
        mpg.setCfg(cfg);  
  
    // 调整 xml 生成目录演示  
         focList.add(new FileOutConfig("/templates/mapper.xml.vm") {  
            @Override  
            public String outputFile(TableInfo tableInfo) {  
                return "/develop/code/xml/" + tableInfo.getEntityName() + ".xml";  
            }  
        });  
        cfg.setFileOutConfigList(focList);  
        mpg.setCfg(cfg);  
  
        // 关闭默认 xml 生成,调整生成 至 根目录  
        TemplateConfig tc = new TemplateConfig();  
        tc.setXml(null);  
        mpg.setTemplate(tc);  
  
        // 自定义模板配置,可以 copy 源码 mybatis-plus/src/main/resources/templates 下面内容修改,  
        // 放置自己项目的 src/main/resources/templates 目录下, 默认名称一下可以不配置,也可以自定义模板名称  
        // TemplateConfig tc = new TemplateConfig();  
        // tc.setController("...");  
        // tc.setEntity("...");  
        // tc.setMapper("...");  
        // tc.setXml("...");  
        // tc.setService("...");  
        // tc.setServiceImpl("...");  
    // 如上任何一个模块如果设置 空 OR Null 将不生成该模块。  
        // mpg.setTemplate(tc);  
  
        // 执行生成  
        mpg.execute();  
  
        // 打印注入设置【可无】  
        System.err.println(mpg.getCfg().getMap().get("abc"));  
    }  
  
}  

Note: Please modify the content in the middle by yourself, the annotation is very clear.

After the code is successfully generated, just copy the generated code to your project. This thing saves us a lot of time and energy!

**

The following are annotations, taken from official documents: Annotations**

Table name annotation @TableName

com.baomidou.mybatisplus.annotations.TableName

value description

value ---------- table name (default empty)

resultMap ---------- xml field mapping resultMap ID

Primary key annotation @TableId

com.baomidou.mybatisplus.annotations.TableId

value description

value ---------- field value (hump case naming method, the value can be absent)

type ----------Primary key ID strategy type (default INPUT, globally enabled is ID_WORKER)
currently does not support composite primary keys

Field annotation @TableField

com.baomidou.mybatisplus.annotations.TableField

value description

value ---------- field value (hump case naming method, the value can be absent)

el ---------- See notes for details

exist ---------- Whether it is a database table field (default true exists, false does not exist)

strategy ---------- field verification (default non-null judgment, check

com.baomidou.mybatisplus.enums.FieldStrategy )
.
fill ---------- field filling mark ( FieldFill, used with autofill)

Field filling strategy FieldFill

value description

DEFAULT ---------- does not process by default

INSERT ----------Insert fill fields

UPDATE ----------Update filled fields

INSERT_UPDATE ---------- Insert and update fill fields

Sequence primary key strategy annotation @KeySequence

com.baomidou.mybatisplus.annotations.KeySequence

value description

value ---------- sequence name

clazz ----------id type

Optimistic lock mark annotation ----------@Version

com.baomidou.mybatisplus.annotations.Version

Exclude non-table fields, see documentation FAQ section!

Summary: The purpose of MP is to simplify development, but it is easy to cause confusion in the code level while providing convenience. We may write a large amount of data logic into the service layer or even the controller layer, making the code difficult to read. It’s too much to go too far. When using MP, you must do analysis, and don’t hand over all data operations to MP. After all, MP is just an enhancement tool of mybatis, and it does not invade the native functions of mybatis. While using the enhanced functions of MP, the functions of native mybatis can still be used normally.

Reposted from: The difference between Mybatis-Plus and Mybatis_mybatis and mybatisplus_Hangzhou Java Development Guo Jing's Blog-CSDN Blog

Guess you like

Origin blog.csdn.net/fuhanghang/article/details/131931256