Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Spring Data fills @LastModifiedDate by not @CreatedDate

I have following Spring Boot sample application. The crazy thing is if I add @EnableMongoAuditing annotation on SampleApplication bean, lastModifiedDate would be filled by createDate would not. Why is that? I searched the web and many people had problems on emptying createDate during an update, but I don't have an update.

Document class:

@Document
public class SampleBean implements Persistable<String> {

    @Id
    public String id;
    @CreatedDate
    public LocalDateTime createDate;
    @LastModifiedDate
    public LocalDateTime lastModifiedDate;

    public String name;

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

    @Override
    public boolean isNew() {
        return id != null;
    }
}

Repository Interface:

@Repository
public interface SampleBeanRepository extends MongoRepository<SampleBean, String> {
}

Rest Controller:

@RestController
public class WebService {

    @Autowired
    private SampleBeanRepository repository;

    @RequestMapping("/insert")
    public String insert() {
        SampleBean sampleBean = new SampleBean();
        sampleBean.name = "Prefix" + new Random().nextInt(1000);
        repository.insert(sampleBean);
        return "done";
    }

    @RequestMapping("/")
    public Collection<SampleBean> home() {
        return repository.findAll();
    }

}

Application Config:

@SpringBootApplication
@EnableMongoAuditing
public class ApplicationConfig {

    public static void main(String[] args) {
        SpringApplication.run(ApplicationConfig.class, args);
    }
}
like image 327
Amir Pashazadeh Avatar asked Jul 10 '17 14:07

Amir Pashazadeh


1 Answers

Your isNew() strategy is the culprit here. Since you have set condition as id != null. Everytime your SampleBean is created there will be no id set as per your code snippet, the isNew() method will return as false hence only LastModifiedDate will be set by the framework. Either change the isNew() method condition to return id == null; or just don't implement Persistable interface whatever default strategy for isNew will be picked.

like image 104
Sunand Padmanabhan Avatar answered Oct 13 '22 00:10

Sunand Padmanabhan