Jpa 實(shí)現(xiàn)自動更新表中的創(chuàng)建日期和修改時間
一般來說創(chuàng)建時間和修改時間 兩個字段是一個實(shí)體類必備的。
在阿里Java開發(fā)手冊中也對此的說明:
【強(qiáng)制】表必備三字段:id, create_time, update_time。
說明:其中 id 必為主鍵,類型為 bigint unsigned、單表時自增、步長為 1。create_time, update_time 的類型均為 datetime 類型,前者現(xiàn)在時表示主動式創(chuàng)建,后者過去分詞表示被動式更新。
mysql 實(shí)現(xiàn)添加時間自動添加更新時間自動更新
在JPA 中也是支持新的數(shù)據(jù)保存是自動寫入創(chuàng)建時間,當(dāng)數(shù)據(jù)有修改時 自動記錄修改時間。在SpringBoot 的啟動類上加 @EnableJpaAuditing 來開啟時間的支持, 在字段上使用 @CreatedDate 和@LastModifiedDate 注解來即可完成時間的自動更新。
實(shí)例:
@EnableJpaAuditing
@SpringBootApplication
public class StudentApplication {
public static void main(String[] args) {
SpringApplication.run(StudentApplication.class, args);
}
}
@EntityListeners(value = AuditingEntityListener.class)
@Getter
@Setter
@Entity
public class StudentEntity {
....
@CreatedDate
@Column(nullable = false, updatable = false)
private LocalDateTime createTime;
@LastModifiedDate
@Column()
private LocalDateTime updateTime;
...
}
由于這兩個字段所有實(shí)體類都有,所以可以將它們抽取到一個通用的類里面,其他實(shí)體類需要時直接繼承即可。
/**
* 所有類的超類
* 自動更新創(chuàng)建時間和更新時間
*
* @author peter
*
**/
@MappedSuperclass
@EntityListeners(value = AuditingEntityListener.class)
@Getter
@Setter
public abstract class AbstractBaseTimeEntity {
@CreatedDate
@Column(nullable = false, updatable = false)
private LocalDateTime createTime;
@LastModifiedDate
@Column()
private LocalDateTime updateTime;
}
@Entity
@Data
public class StudentEntity extends AbstractBaseTimeEntity {
....
}
補(bǔ)充:Jpa配置實(shí)體類創(chuàng)建時間更新時間自動賦值,@CreateDate,@LastModifiedDate
操作數(shù)據(jù)庫映射實(shí)體類時,通常需要記錄createTime和updateTime,如果每個對象新增或修改去都去手工操作創(chuàng)建時間、更新時間,會顯得比較繁瑣。
Springboot jpa提供了自動填充這兩個字段的功能,簡單配置一下即可。@CreatedDate、@LastModifiedDate、@CreatedBy、@LastModifiedBy前兩個注解就是起這個作用的,后兩個是設(shè)置修改人和創(chuàng)建人的,這里先不討論。
首先,我們的很多實(shí)體類都是需要創(chuàng)建時間和更新時間的,我們不想在每個實(shí)體類里都去定義這兩個字段,那么我們把它抽取到基類中,讓實(shí)體類去繼承它。
package com.tianyalei.testautotime.entity;
import org.springframework.data.annotation.CreatedDate;
import org.springframework.data.annotation.LastModifiedDate;
import org.springframework.data.jpa.domain.support.AuditingEntityListener;
import javax.persistence.*;
/**
* Created by wuwf on 17/4/21.
*/
@MappedSuperclass
@EntityListeners(AuditingEntityListener.class)
public abstract class BaseEntity {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
protected Integer id;
@CreatedDate
private Long createTime;
@LastModifiedDate
private Long updateTime;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public Long getCreateTime() {
return createTime;
}
public void setCreateTime(Long createTime) {
this.createTime = createTime;
}
public Long getUpdateTime() {
return updateTime;
}
public void setUpdateTime(Long updateTime) {
this.updateTime = updateTime;
}
}
AuditingEntityListener標(biāo)簽開啟后,下面的時間標(biāo)簽才會生效。
然后還需要在啟動類加上@EnableJpaAuditing注解。
做完這些,我們來測試一下,新建個Springboot項目,配置一下數(shù)據(jù)庫信息
spring: jpa: database: mysql show-sql: true hibernate: ddl-auto: update datasource: type: com.alibaba.druid.pool.DruidDataSource driver-class-name: com.mysql.jdbc.Driver url: jdbc:mysql://localhost:3306/test username: root password:
新建個普通的實(shí)體類。
package com.tianyalei.testautotime.entity;
import javax.persistence.Entity;
@Entity
public class Post extends BaseEntity {
private String title;
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
}
測試類:
import com.tianyalei.testautotime.entity.Post;
import com.tianyalei.testautotime.repository.PostRepository;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
@RunWith(SpringRunner.class)
@SpringBootTest
public class TestautotimeApplicationTests {
@Autowired
PostRepository postRepository;
@Test
public void save() {
Post post = new Post();
post.setTitle("title0");
postRepository.save(post);
}
// @Test
// public void update() {
// Post post = postRepository.findOne(1);
// post.setTitle(“title1”);
// postRepository.save(post);
// }
}
先試試新增。
可以看到已經(jīng)被自動賦值了。
然后試試update,將上面的update的注釋放開。
可以看到更新時間也自動修改了。
需注意,如果你沒有修改任何字段的值的話,即便走了save方法,updateTime也是不會更改的。
以上為個人經(jīng)驗,希望能給大家一個參考,也希望大家多多支持腳本之家。如有錯誤或未考慮完全的地方,望不吝賜教。
相關(guān)文章
解決java調(diào)用dll報Unable to load library錯誤的問題
這篇文章主要介紹了解決java調(diào)用dll報Unable to load library錯誤的問題。具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2020-11-11
深入理解Java中Filter的作用種類及應(yīng)用場景
Filter(過濾器)是Java Web中的一種重要組件,可以對請求和響應(yīng)進(jìn)行攔截處理,對數(shù)據(jù)進(jìn)行過濾和處理。Filter可以實(shí)現(xiàn)許多功能,如:鑒權(quán)、日志記錄、字符編碼轉(zhuǎn)換、數(shù)據(jù)壓縮、請求重定向等等2023-04-04
解決JAVA非對稱加密不同系統(tǒng)加密結(jié)果不一致的問題
這篇文章主要介紹了解決JAVA非對稱加密不同系統(tǒng)加密結(jié)果不一致的問題,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2020-10-10
JavaWeb評論功能實(shí)現(xiàn)步驟以及代碼實(shí)例
項目初始版本上線,有時間寫點(diǎn)東西記錄一下項目中的心得體會,通過這個項目學(xué)習(xí)了很多,要寫下來的有很多,先從評論功能開始吧,下面這篇文章主要給大家介紹了關(guān)于JavaWeb評論功能實(shí)現(xiàn)步驟以及代碼的相關(guān)資料,需要的朋友可以參考下2023-01-01
Spring的事件機(jī)制知識點(diǎn)詳解及實(shí)例分析
在本篇內(nèi)容里小編給大家分享的是一篇關(guān)于Spring的事件機(jī)制知識點(diǎn)詳解及實(shí)例分析,有需要的朋友么可以參考下。2021-12-12
SpringBoot使用EmbeddedDatabaseBuilder進(jìn)行數(shù)據(jù)庫集成測試
在開發(fā)SpringBoot應(yīng)用程序時,我們通常需要與數(shù)據(jù)庫進(jìn)行交互,為了確保我們的應(yīng)用程序在生產(chǎn)環(huán)境中可以正常工作,我們需要進(jìn)行數(shù)據(jù)庫集成測試,在本文中,我們將介紹如何使用 SpringBoot 中的 EmbeddedDatabaseBuilder 來進(jìn)行數(shù)據(jù)庫集成測試2023-07-07

