我已经实施了spring数据jpa审计。以下是我的配置文件
@Configuration
@ComponentScan(basePackages = "com.myapplication.test")
@EnableWebMvc
@EnableTransactionManagement
@EnableJpaRepositories(basePackages = "com.myapplication.test.repository")
@EnableJpaAuditing(auditorAwareRef = "auditorProvider", dateTimeProviderRef = "dateTimeProvider")
@EnableSpringDataWebSupport
public class ApplicationConfiguration {
private static final Logger loggger = Logger.getLogger(ApplicationConfiguration.class);
@Autowired
private ConfigurationProperties configProps;
@Bean("auditorProvider")
public AuditorAware<Integer> auditorProvider() {
return () -> {
AuthenticationToken authentication = (AuthenticationToken) SecurityContextHolder.getContext().getAuthentication();
return (authentication != null && authentication.isAuthenticated()) ? authentication.getUser().getUserId() : null;
};
}
@Bean
public DateTimeProvider dateTimeProvider() {
return () -> GregorianCalendar.from(ZonedDateTime.now());
}
}
这是我的实体超类
@MappedSuperclass
@EntityListeners(AuditingEntityListener.class)
public abstract class BaseEntity {
@JsonIgnore
@Column(name = "created_by", updatable = false)
private Integer createdBy;
@JsonIgnore
@CreationTimestamp
@Temporal(TemporalType.TIMESTAMP)
@Column(name = "created_on", updatable = false)
private Date createdOn;
@JsonIgnore
@Column(name = "last_updated_by")
private Integer updatedBy;
@JsonIgnore
@UpdateTimestamp
@Temporal(TemporalType.TIMESTAMP)
@Column(name = "last_updated_on")
private Date updatedOn;
}
auditorProvider从Spring Security上下文中获取用户ID。我使用过spring-security-oauth2。
低于我所拥有的库的版本
<spring.version>4.3.6.RELEASE</spring.version>
<hibernate.version>5.2.9.Final</hibernate.version>
<springsecurity.version>4.1.4.RELEASE</springsecurity.version>
<springsecurityoauth2.version>2.0.12.RELEASE</springsecurityoauth2.version>
当我保存实体时,不会调用审计方法(在调试中),并且表中不会更新创建/更新的字段。
答案 0 :(得分:0)
不应使用hibernate注释,而应使用spring数据:
@Column(name = "created_date", nullable = false, updatable = false)
@CreatedDate
private long createdDate;
@Column(name = "modified_date")
@LastModifiedDate
private long modifiedDate;
这对我来说总是有用,如本教程中所指定:Jpa Auditing