栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

Mybatis-plus实现主键自增和自动注入时间的示例代码

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

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;


@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());
  }
}

到此这篇关于Mybatis-plus实现主键自增和自动注入时间的示例代码的文章就介绍到这了,更多相关Mybatis-plus 主键自增和自动注入时间内容请搜索考高分网以前的文章或继续浏览下面的相关文章希望大家以后多多支持考高分网!

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/133081.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号