Spring 数据 MongoDB 注解 @CreatedDate 在手动分配 ID 时不起作用

Spring Data MongoDB Annotation @CreatedDate isn't working, when ID is assigned manually

我正在尝试使用审核在我的对象中保存 dateCreateddateUpdated,但由于我手动设置了 ID,所以还有一些额外的工作。

遵循 Oliver Gierke 在 DATAMONGO-946 中的建议 我正在尝试弄清楚如何正确实施它。

作为上述 Jira 任务中的原始发布者,我从这里下载示例 https://github.com/spring-guides/gs-accessing-data-mongodb.git 并对其进行了一些修改:

package hello;

import org.springframework.data.annotation.CreatedDate;
import org.springframework.data.annotation.Id;
import org.springframework.data.annotation.LastModifiedDate;
import org.springframework.data.domain.Persistable;

import java.util.Date;

public class Customer implements Persistable<String> {
    @Id
    private String id;
    @CreatedDate
    private Date createdDate;
    @LastModifiedDate
    private Date lastModifiedDate;
    private String firstName;
    private String lastName;
    private boolean persisted;

    public Customer() {
    }

    public Customer(String firstName, String lastName) {
        this.firstName = firstName;
        this.lastName = lastName;
    }

    public void setPersisted(boolean persisted) {
        this.persisted = persisted;
    }

    @Override
    public String getId() {
        return id;
    }

    public void setId(String id) {
        this.id = id;
    }

    @Override
    public boolean isNew() {
        return !persisted;
    }

    @Override
    public String toString() {
        return String.format(
                "Customer[id=%s, createdDate=%s, lastModifiedDate=%s, firstName='%s', lastName='%s']",
                id, createdDate, lastModifiedDate, firstName, lastName);
    }
}

package hello;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.data.mongodb.config.EnableMongoAuditing;

@SpringBootApplication
@EnableMongoAuditing
public class Application implements CommandLineRunner {

    @Autowired
    private CustomerRepository repository;

    public static void main(String[] args) {
        SpringApplication.run(Application.class, args);
    }

    @Override
    public void run(String... args) throws Exception {

        repository.deleteAll();

        // create a customer
        Customer c = new Customer("Alice", "Smith");
        c.setId("test_id");

        // save a customer
        repository.save(c);

        // fetch all customers
        System.out.println("Customers found with findAll():");
        System.out.println("-------------------------------");
        for (Customer customer : repository.findAll()) {
            System.out.println(customer);
        }
        System.out.println();

        // create another customer with same id
        c = new Customer("Bob", "Smith");
        c.setId("test_id");
        c.setPersisted(true);
        repository.save(c);

        // fetch all customers
        System.out.println("Customers found with findAll():");
        System.out.println("-------------------------------");
        for (Customer customer : repository.findAll()) {
            System.out.println(customer);
        }
        System.out.println();
    }
}

执行结果是这样的:

Customers found with findAll():
-------------------------------
Customer[id=test_id, createdDate=Wed Feb 24 00:43:47 WITA 2016, lastModifiedDate=Wed Feb 24 00:43:47 WITA 2016, firstName='Alice', lastName='Smith']

Customers found with findAll():
-------------------------------
Customer[id=test_id, createdDate=null, lastModifiedDate=Wed Feb 24 00:43:47 WITA 2016, firstName='Bob', lastName='Smith']

createdDate 对象更新后变为 null

我在这里错过了什么?以及如何正确实施 Persistable 以使审计正常工作?

您的代码按预期工作。实施 Persistable 后,您可以看到 @CreatedDate 注释正在工作。

save 的第二次调用中确保 createdDatenull,因为该对象已经存在于数据库中并且您用 createdDate = null 更新了它。从 @CreatedDate:

的文档中可以看出

@CreatedDate annotation. This identifies the field whose value is set when the entity is persisted to the database for the first time.

所以不要在第二次调用时用 null 覆盖你的 createdDate 你应该用 c = repository.findOne("test_id"); 从数据库中检索你的客户然后更新它。

最简单的解决方案是向您的客户 class 添加一个版本 属性(用 @Version 注释)并保持未初始化状态。这会将值 0 分配给任何新创建的对象,这反过来告诉 spring 这是一个新对象。

  @Version private Long version;

注意:此对象的每次修改都会自动增加此版本

@EnableMongoAuditing 添加到 spring 启动应用程序中的主要方法。