@CreatedDate注释不适用于mysql

福赞:

我是Spring的新手,我对@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() {
    }

这没用。对于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() {
    }

这实际上将时间戳存储在数据库中。我的问题是我遵循的大多数教程都建议我不需要new Date()获取当前时间戳。看来我确实需要那个。我有什么想念的吗?

莫西·阿拉德(​​Moshe Arad):

@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;
    }

}

您可以在此处编写任何适合您需求的功能,但是您肯定必须有一个引用实现AuditorAware的类的bean。

同样重要的第二部分是创建一个返回带有注解的类的bean @EnableJpaAuditing,如下所示:

@Configuration
@EnableJpaAuditing
public class AuditorConfig {

    @Bean
    public CustomAuditorAware auditorProvider(){
        return new CustomAuditorAware();
    }
}

如果您的毒药是XML配置,请执行以下操作:

<bean id="customAuditorAware" class="org.moshe.arad.general.CustomAuditorAware" />
    <jpa:auditing auditor-aware-ref="customAuditorAware"/>

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章