Mybatis-plus實現(xiàn)主鍵自增和自動注入時間的示例代碼
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了,沖突!
連接數(shù)據(jù)庫
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),同時將數(shù)據(jù)庫中的id字段設置為自增即可。
編寫配置類來進行自動注入時間(繼承元數(shù)據(jù)類并重寫它的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()); } }
到此這篇關于Mybatis-plus實現(xiàn)主鍵自增和自動注入時間的示例代碼的文章就介紹到這了,更多相關Mybatis-plus 主鍵自增和自動注入時間內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
相關文章
SpringBoot整合iText7導出PDF及性能優(yōu)化方式
在SpringBoot項目中整合iText7庫以導出PDF文件,不僅能夠滿足報告生成需求,而且可以處理復雜的文檔布局與樣式,整合步驟包括添加Maven依賴、編寫PDF生成代碼,性能優(yōu)化方面,建議使用流式處理、緩存樣式與字體、優(yōu)化HTML/CSS結構、采用異步處理2024-09-09Maven方式構建SpringBoot項目的實現(xiàn)步驟(圖文)
Maven是一個強大的項目管理工具,可以幫助您輕松地構建和管理Spring Boot應用程序,本文主要介紹了Maven方式構建SpringBoot項目的實現(xiàn)步驟,具有一定的參考價值,感興趣的可以了解一下2023-09-09MyBatis通用Mapper實現(xiàn)原理及相關內(nèi)容
今天小編就為大家分享一篇關于MyBatis通用Mapper實現(xiàn)原理及相關內(nèi)容,小編覺得內(nèi)容挺不錯的,現(xiàn)在分享給大家,具有很好的參考價值,需要的朋友一起跟隨小編來看看吧2018-12-12關于Spring?Boot項目的?log4j2?核彈漏洞問題(一行代碼配置搞定)
相信昨天,很多小伙伴都因為Log4j2的史詩級漏洞忙翻了吧,不過我看到群里發(fā)出來的各種修復方法,還真是不好看...所以這里也提一下Spring Boot用戶怎么修復最簡單吧,對Spring Boot log4j2 核彈漏洞問題感興趣的朋友參考下吧2021-12-12Java以編程方式實現(xiàn)JAR文件的創(chuàng)建
在這篇文章中,我們將為大家詳細介紹一下利用Java語言以編程方式創(chuàng)建jar文件的過程。文中的示例代碼講解詳細,感興趣的可以了解一下2022-07-07