操作數據庫映射實體類時,通常需要記錄createTime和updateTime,如果每個對象新增或修改去都去手工操作創建時間、更新時間,會顯得比較繁瑣。
Springboot jpa提供了自動填充這兩個字段的功能,簡單配置一下即可。@CreatedDate、@LastModifiedDate、@CreatedBy、@LastModifiedBy前兩個註解就是起這個作用的,後兩個是設置修改人和創建人的,這裡先不討論。
JPA Audit
- @CreatedDate
- 表示該字段為創建時間時間字段,在這個實體被insert的時候,會設置值
- @CreatedBy
- 表示該字段為創建人,在這個實體被insert的時候,會設置值
- @LastModifiedDate、@LastModifiedBy同理。
如何使用?
首先申明實體類,需要在類上加上註解
@EntityListeners(AuditingEntityListener.class)
其次在application啟動類中加上註解
@EnableJpaAuditing
同時在需要的字段上加上
@CreatedDate、@CreatedBy、@LastModifiedDate、@LastModifiedBy
等註解。
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 charleslai
*/
@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;
}
}
新建個普通的實體類。
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);
// }
}
先試試新增。
可以看到已經被自動賦值了。
然後試試update,將上面的update的註釋放開。
可以看到更新時間也自動修改了。
需注意,如果你沒有修改任何字段的值的話,即便走了save方法,updateTime也是不會更改的。
閱讀更多 養碼場007 的文章