@CreatedDate注释不适用于mysql
我是Spring的新手,我对@CreatedDate注释在实体中的工作方式感到困惑.
I am new to spring and I am confused how @CreatedDate annotation works in an entity.
我做了一个google搜索,有很多解决方案,但是除了一个解决方案外,没有一个对我有用.我很困惑为什么?
I did a google search and there were many solutions, but none of them worked for me except one. I am confused why?
这是我首先尝试的
@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() {
}
它没有用.我在created
列中的值为NULL.
It did not work. I got NULL for the value in created
column.
然后我做到了.
@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() {
}
这实际上将时间戳存储在db中.我的问题是我遵循的大多数教程都建议我不需要new Date()
即可获取当前时间戳.看起来我确实需要那个.有什么我想念的吗?
This actually stored the time stamp in the db. My question is most of the tutorials I followed suggested that I do not need new Date()
to get the current time stamp. Looks like I do need that. Is there anything I am missing?
如果仅将@EntityListeners(AuditingEntityListener.class)
放在实体上,则@CreatedDate
本身将无法工作.为了工作,您必须做一些更多的配置.
The @CreatedDate
won't work by itself if you just put @EntityListeners(AuditingEntityListener.class)
on your entities. In order, it'll work you have to do a little more configuration.
假设在您的数据库中,@CreatedDate
的字段为String类型,并且您想返回当前登录的用户作为@CreatedDate
的值,然后执行以下操作:
Let's say that in your DB the field of @CreatedDate
is String type, and you want to return the user that is currently logged in as a value for @CreatedDate
, then do this:
public class CustomAuditorAware implements AuditorAware<String> {
@Override
public String getCurrentAuditor() {
String loggedName = SecurityContextHolder.getContext().getAuthentication().getName();
return loggedName;
}
}
您可以在此处编写任何适合您需求的功能,但是您肯定必须有一个引用实现AuditorAware
You can write there any functionality that fits your needs, but you certainly must have a bean that reference to a class that implements `AuditorAware
同样重要的是,第二部分是创建一个返回带有@EnableJpaAuditing
注释的类的Bean,如下所示:
The second part and equally important, is to create a bean that returns that class with annotation of @EnableJpaAuditing
, like this:
@Configuration
@EnableJpaAuditing
public class AuditorConfig {
@Bean
public CustomAuditorAware auditorProvider(){
return new CustomAuditorAware();
}
}
如果您的毒药是XML配置,请执行以下操作:
if your poison is XML configuration then do this:
<bean id="customAuditorAware" class="org.moshe.arad.general.CustomAuditorAware" />
<jpa:auditing auditor-aware-ref="customAuditorAware"/>