最新下载
热门教程
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
Mybatis-plus实现主键自增和自动注入时间代码示例
时间:2020-07-20 编辑:袖梨 来源:一聚教程网
本篇文章小编给大家分享一下Mybatis-plus实现主键自增和自动注入时间代码示例,文章代码介绍的很详细,小编觉得挺不错的,现在分享给大家供大家参考,有需要的小伙伴们可以来看看。
mybatis-plus依赖导入
com.baomidou mybatis-plus-boot-starter 3.3.2
建议使用3.3.0后的版本。
导入mybatis-plus就不用导入mybatis了,冲突!
连接数据库
spring.datasource.username=root spring.datasource.password=19981204 spring.datasource.url=jdbc:mysql://localhost:3306/mybatis_plus?serverTimezone=Asia/Shanghai&useUnicode=true&characterEncoding=utf-8 spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver mybatis-plus.configuration.log-impl=org.apache.ibatis.logging.stdout.StdOutImpl//配置默认日志
设置主键自增
@Data @AllArgsConstructor @NoArgsConstructor public class User { @TableId(type = IdType.AUTO) private Long id; private String name; private Integer age; private String email; }
使用注解 @TableId(type=IdType.AUTO),同时将数据库中的id字段设置为自增即可。
编写配置类来进行自动注入时间(继承元数据类并重写它的insertFill和updateFill方法)
使用注解@TableFiled(fill=FieldFill.INSERT)
@Data @AllArgsConstructor @NoArgsConstructor public class User { @TableId(type = IdType.AUTO) private Long id; private String name; private Integer age; private String email; @TableField(fill = FieldFill.INSERT) private LocalDateTime createTime; @TableField(fill = FieldFill.INSERT_UPDATE) private LocalDateTime updateTime; }
package com.ls.handler; import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler; import org.apache.ibatis.reflection.MetaObject; import org.springframework.stereotype.Component; import java.time.LocalDateTime; /** * @author dell */ @Component public class MyMetaObjectHandler implements MetaObjectHandler { @Override public void insertFill(MetaObject metaObject) { this.strictInsertFill(metaObject,"createTime", LocalDateTime.class,LocalDateTime.now()); this.strictUpdateFill(metaObject,"updateTime",LocalDateTime.class,LocalDateTime.now()); } @Override public void updateFill(MetaObject metaObject) { this.strictUpdateFill(metaObject,"updateTime",LocalDateTime.class,LocalDateTime.now()); } }
相关文章
- SpringBoot自定义bean绑定解析 10-24
- Javaweb工程运行报错HTTP Status 404解决教程 10-20
- JAVA获取jvm和操作系统相关信息方法 10-20
- BeanFactory和FactoryBean的区别讲解 10-20
- 微信小程序的宿主环境实现教程 10-10
- dispatchEvent解决重叠元素响应事件教程 10-10