在spring jpa中,支持在字段或者方法上进行注解@CreatedDate
、@CreatedBy
、@LastModifiedDate
、@LastModifiedBy
,从字面意思可以很清楚的了解,这几个注解的用处。
@CreatedDate
:表示该字段为创建时间时间字段,在这个实体被insert的时候,会设置值
@CreatedBy
:表示该字段为创建人,在这个实体被insert的时候,会设置值
@LastModifiedDate
、@LastModifiedBy
同理。
如何使用?
首先申明实体类,需要在类上加上注解 @EntityListeners(AuditingEntityListener.class)
,
其次在 application 启动类中加上注解 EnableJpaAuditing
,
同时在需要的字段上加上@CreatedDate
、@CreatedBy
、@LastModifiedDate
、@LastModifiedBy
等注解。
这个时候,在jpa.save方法被调用的时候,时间字段会自动设置并插入数据库,但是CreatedBy和LastModifiedBy并没有赋值,因为需要实现AuditorAware
接口来返回你需要插入的值。
1 2 3 4 5 6 7 8 9 10 11 12
| import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.boot.builder.SpringApplicationBuilder; import org.springframework.context.annotation.Import; import org.springframework.data.jpa.repository.config.EnableJpaAuditing;
@SpringBootApplication @EnableJpaAuditing public class WalletApplication { public static void main(String[] args) { new SpringApplicationBuilder(WalletApplication.class).web(true).run(args); } }
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27
| import org.springframework.context.annotation.Configuration; import org.springframework.data.domain.AuditorAware; import org.springframework.security.core.context.SecurityContext; import org.springframework.security.core.context.SecurityContextHolder;
@Configuration public class UserIDAuditorBean implements AuditorAware<Long> { @Override public Long getCurrentAuditor() { SecurityContext ctx = SecurityContextHolder.getContext(); if (ctx == null) { return null; } if (ctx.getAuthentication() == null) { return null; } if (ctx.getAuthentication().getPrincipal() == null) { return null; } Object principal = ctx.getAuthentication().getPrincipal(); if (principal.getClass().isAssignableFrom(Long.class)) { return (Long) principal; } else { return null; } } }
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41
| import java.util.Date;
import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.EntityListeners; import javax.persistence.Table;
import org.springframework.data.annotation.CreatedDate; import org.springframework.data.annotation.LastModifiedDate; import org.springframework.data.jpa.domain.support.AuditingEntityListener;
@Entity @Table(name = "store_source_bind") @EntityListeners(AuditingEntityListener.class) public class Student {
@Column(name = "create_time") @CreatedDate private Date createTime;
@Column(name = "create_by") @CreatedBy private Long createBy;
@Column(name = "lastmodified_time") @LastModifiedDate private Date lastmodifiedTime;
@Column(name = "lastmodified_by") @LastModifiedBy private String lastmodifiedBy; }
|