@CreatedDate注释不适用于mysql

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)

  • 谢谢,这帮助我解决了“@CreatedDate”注释不起作用的问题。不建议将此注释与“@SpringBootApplication”一起使用。我在测试时遇到以下错误: _java.lang.IllegalArgumentException: JPA 元模型不能为空!_ 。请仔细阅读[此](/sf/answers/4242594961/)答案。人们还应该确保不相关的切片在测试时也不会干扰。 (3认同)

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)

  • 我有相同的配置,但这会将值设置为`@ CreatedBy`和`@ LastModifiedBy`注释字段.注释为"@ LastModifiedDate"和"@ CreatedDate"的其他字段始终为null.如何解决这个问题? (5认同)

归档时间:

查看次数:

9527 次

最近记录:

6 年,2 月 前