MyBatisPlus使用中几个需要注意的点
一、需要在pom中添加的坐标和解释
<!-- MyBatisPlus包 -->
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-boot-starter</artifactId>
<version>3.3.1</version>
</dependency>
<!--代码生成器,自动生成bean,service,controller,mapper-->
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-generator</artifactId>
<version>3.3.1</version>
</dependency>
<!--代码生成器-默认模板引擎-->
<dependency>
<groupId>org.apache.velocity</groupId>
<artifactId>velocity-engine-core</artifactId>
<version>2.2</version>
</dependency>
<!--代码生成器-可选模板引擎-->
<dependency>
<groupId>org.freemarker</groupId>
<artifactId>freemarker</artifactId>
<version>2.3.30</version>
</dependency>
二、插入时主键id的问题
对象的主键字段需要添加如下设置
@TableId(value = "id", type = IdType.AUTO)
private Integer id;
其中IdType的可选值为
public enum IdType {
AUTO(0),//主键自增
NONE(1),//不为主键
INPUT(2),//手动输入主键
ASSIGN_ID(3),//分配ID,主键类型为Number(Long和Integer)或String
ASSIGN_UUID(4)//分配UUID,主键类型为String
}
AUTO
id设置成自增的时候,insert的时候就id就会被忽略,即使设置了值也无效;
返回的值可以通过getId
获取插入数据的主键id值
userMapper.insert(user);
Integer id = user.getId();
INPUT
如果想要手动设置插入的id,主键类型可是设置为input,设置之后在insert的时候就必须手动
设置id值,不然就会insert失败。返回值中自然也就已经有了插入的数据id。
三、设置显示sql日志
在.yml文件中设置
#mybatisplus配置
mybatis-plus:
configuration:
log-impl: org.apache.ibatis.logging.stdout.StdOutImpl #开启日志打印
四、代码生成器
需要的坐标已在一中已经说明
创建CodeGenerator代码生成类
package com.hao.springcloud.cloudproviderpayment8001.utils;
import com.baomidou.mybatisplus.annotation.DbType;
import com.baomidou.mybatisplus.core.exceptions.MybatisPlus