简述:
使用Mybatis-Plus新增数据并返回数据主键值
环境:
DB:Postgre SQL
插件:Mybatis-Plus
Maven依赖:
DB:
<dependency>
<groupId>org.postgresql</groupId>
<artifactId>postgresql</artifactId>
</dependency>
Mybatis-Plus:
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus</artifactId>
<version>2.1.9</version>
</dependency>
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatisplus-spring-boot-starter</artifactId>
<version>1.0.5</version>
</dependency>
application.yml配置:
Mybatis-Plus:
#mybatis
mybatis-plus:
mapper-locations: classpath*:mapper/**/*.xml
#实体扫描,多个package用逗号或者分号分隔
typeAliasesPackage: com.geohey.entity
global-config:
#主键类型 0:"数据库ID自增", 1:"用户输入ID",2:"全局唯一ID (数字类型唯一ID)", 3:"全局唯一ID UUID";
id-type: 0
#字段策略 0:"忽略判断",1:"非 NULL 判断"),2:"非空判断"
field-strategy: 1
#驼峰下划线转换
db-column-underline: true
#刷新mapper 调试神器
refresh-mapper: true
#数据库大写下划线转换
#capital-mode: true
#序列接口实现类配置
#key-generator: com.baomidou.springboot.xxx
#逻辑删除配置
logic-delete-value: -1
logic-not-delete-value: 0
#自定义填充策略接口实现
#meta-object-handler: com.baomidou.springboot.xxx
#自定义SQL注入器
sql-injector: com.baomidou.mybatisplus.mapper.LogicSqlInjector
configuration:
map-underscore-to-camel-case: true
cache-enabled: false
call-setters-on-nulls: true
正文:
1.编写实体类。
实体类中要定义DB表中的主键字段,用于接收新增数据后的主键值。
例:
注:DB中字段什么样,实体类中就什么样,不要简写,不要驼峰。
2.定义标签。
模板:
<insert id="接口名" parameterType="XXX" useGeneratedKeys="true" keyProperty="row_id">
insert into tab (
column1,
column2,
···
)
values (
#{pro1},
#{pro2},
···
)
</insert>
注:标签中的"keyProperty"属性要指定DB表中的主键字段,也是实体类中定义的主键字段属性,三者名字要保持一致。
3.执行成功后,实体类中的主键属性会自动填充上新数据的主键值。
执行前:
执行后:
拓展:主键默认生成UUID,语句:replace(cast(uuid_generate_v4() as VARCHAR), ‘-’,’’)
2021年11月2日 天气·晴