Spring JPA 使用CreatedDateCreatedBy自动生成时间和修改者

操作数据库映射实体类时,通常需要记录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也是不会更改的。


分享到:


相關文章: