Mybatis-plus實現主鍵自增和自動注入時間的示例程式碼
阿新 • • 發佈:2020-07-21
mybatis-plus依賴匯入
<dependency> <groupId>com.baomidou</groupId> <artifactId>mybatis-plus-boot-starter</artifactId> <version>3.3.2</version> </dependency>
建議使用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方法)
@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.now()); } @Override public void updateFill(MetaObject metaObject) { this.strictUpdateFill(metaObject,LocalDateTime.now()); } }
到此這篇關於Mybatis-plus實現主鍵自增和自動注入時間的示例程式碼的文章就介紹到這了,更多相關Mybatis-plus 主鍵自增和自動注入時間內容請搜尋我們以前的文章或繼續瀏覽下面的相關文章希望大家以後多多支援我們!