在spring jpa中,支持在字段或者方法上進行註解@CreatedDate、@CreatedBy、@LastModifiedDate、@LastModifiedBy。維護數據庫的建立時間、建立人、最後修改時間、最後修改人。實現步驟以下:spring
@MappedSuperclass @EntityListeners(AuditingEntityListener.class) public class BaseEntity { private static final long serialVersionUID = 7491626901163891174L; @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Long id; @JsonIgnore @Temporal(TemporalType.TIMESTAMP) @CreatedDate @Column(updatable = false) private Date createTime; @JsonIgnore @Temporal(TemporalType.TIMESTAMP) @LastModifiedDate @Column(updatable = false) private Date updateTime; @LastModifiedBy private String updatedBy; //省略getter、setter
@Component("auditorAware") public class AuditorAwareImpl implements AuditorAware<String> { @Override public Optional<String> getCurrentAuditor() { Authentication authentication = SecurityContextHolder.getContext().getAuthentication(); return Optional.of(authentication.getPrincipal().toString()); } }
@SpringBootApplication @EnableCaching(proxyTargetClass = true) @EnableJpaAuditing(auditorAwareRef = "auditorAware") public class TestApplication { }
其中的auditorAwareRef = "auditorAware"就是上面配置的@Component("auditorAware")數據庫