Faw*_*zan 8 java mysql audit-tables spring-data-jpa spring-boot
我是春天的新手,我很困惑@CreatedDate注释在一个实体中是如何工作的.
我做了一个谷歌搜索,有很多解决方案,但除了一个,它们都没有为我工作.我很困惑为什么?
这是我先试过的
@Entity
@EntityListeners(AuditingEntityListener.class)
public class User implements Serializable {
@Id
@GeneratedValue
private Long id;
private String name;
@CreatedDate
private Date created;
public User(String name) {
this.name = name;
}
public User() {
}
Run Code Online (Sandbox Code Playgroud)
那没起效.我在created
列中的值为NULL .
然后我做了这个.
@Entity
@EntityListeners(AuditingEntityListener.class)
public class User implements Serializable {
@Id
@GeneratedValue
private Long id;
private String name;
@CreatedDate
private Date created = new Date();
public User(String name) {
this.name = name;
}
public User() {
}
Run Code Online (Sandbox Code Playgroud)
这实际上将时间戳存储在db中.我的问题是我遵循的大多数教程都表明我不需要new Date()
获取当前时间戳.看起来我确实需要它.有什么我想念的吗?
小智 32
我也有这个问题,你的解决方案帮助了我,谢谢,我添加了一些其他的注释来工作
拳头确保您放入 SpringApplication 配置
@SpringBootApplication
@EnableJpaAuditing
Run Code Online (Sandbox Code Playgroud)
其次,确保你在你需要的实体上使用这个注解
@Entity
@Table
@EntityListeners(AuditingEntityListener.class)
Run Code Online (Sandbox Code Playgroud)
Sup*_*ana 17
您可以使用@CreationTimestamp
并@UpdateTimestamp
像这样:
@CreationTimestamp
private Instant createdAt;
@UpdateTimestamp
private Instant updatedAt;
Run Code Online (Sandbox Code Playgroud)
Mos*_*rad 13
@CreatedDate
如果你只是穿上@EntityListeners(AuditingEntityListener.class)
你的实体,它将无法自行工作.按顺序,你需要做一些配置.
假设您的数据库中的字段@CreatedDate
是String类型,并且您希望将当前登录的用户作为值返回@CreatedDate
,然后执行以下操作:
public class CustomAuditorAware implements AuditorAware<String> {
@Override
public String getCurrentAuditor() {
String loggedName = SecurityContextHolder.getContext().getAuthentication().getName();
return loggedName;
}
}
Run Code Online (Sandbox Code Playgroud)
你可以在那里写任何适合你需要的功能,但是你当然必须有一个bean来引用一个实现`AuditorAware的类
第二部分同样重要的是创建一个bean,它返回带有注释的类@EnableJpaAuditing
,如下所示:
@Configuration
@EnableJpaAuditing
public class AuditorConfig {
@Bean
public CustomAuditorAware auditorProvider(){
return new CustomAuditorAware();
}
}
Run Code Online (Sandbox Code Playgroud)
如果你的毒药是XML配置,那么这样做:
<bean id="customAuditorAware" class="org.moshe.arad.general.CustomAuditorAware" />
<jpa:auditing auditor-aware-ref="customAuditorAware"/>
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
9527 次 |
最近记录: |