@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() 来获取当前时间戳。看起来我确实需要那个。我有什么想念的吗?

原文由 Fawzan 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 743
2 个回答

如果您只是将 @EntityListeners(AuditingEntityListener.class) 放在您的实体上,那么 @CreatedDate 将无法单独工作。为了,它会工作你必须做更多的配置。

假设在您的数据库中, @CreatedDate 的字段是字符串类型,并且您想要返回当前登录的用户作为 @CreatedDate 的值,然后执行以下操作:

 public class CustomAuditorAware implements AuditorAware<String> {

    @Override
    public String getCurrentAuditor() {
        String loggedName = SecurityContextHolder.getContext().getAuthentication().getName();
        return loggedName;
    }

}

您可以在那里编写满足您需要的任何功能,但您肯定必须有一个引用实现`AuditorAware 的类的 bean

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

 @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"/>

原文由 Moshe Arad 发布,翻译遵循 CC BY-SA 3.0 许可协议

我也有这个问题,你的解决方案帮助了我,谢谢,我添加了一些其他注释来工作

拳头确保你放入 SpringApplication 配置

@SpringBootApplication
@EnableJpaAuditing

其次,确保你在你需要的实体上使用这个注解

  @Entity
  @Table
  @EntityListeners(AuditingEntityListener.class)

原文由 Ismail 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题