Setting createdOn and UpdatedOn automatically

折月煮酒 提交于 2019-12-22 18:07:08

问题


I am playing with spring-data and mongodb. What I am trying to achieve is to automaticaly set createdOn and updatedOn dates when I am creating and/or updating an object. So I basically created a "BaseDocument" that holds createdOn and updatedOn date attributes and created an AbstractMongoDbListener so that i can intercept the document before save (onBeforeSave) and then set those dates. The problem is that if i dont add those dates to the constructor of the class that extends BaseDocument, those dates wont get persisted to the database. The subclass needs to have createdOn and updatedOn on its constructor to get those persisted and that is messing with the idea of automating the creation of these dates. What would be a good strategy to implement that?

Thanks in advance!


回答1:


Audit support has been implemented in Spring Data MongoDB 1.2.0. In order to use you need to have joda-time on your classpath and set type of created and modified dates to DateTime. All required steps

  • Add maven dependency
    <dependency>
        <groupId>joda-time</groupId>
        <artifactId>joda-time</artifactId>
        <version>2.2</version>
    </dependency>
  • Add support to auditing in Spring configuration
    <mongo:auditing />
  • Annotate properties in your classes like:
    @CreatedDate
    private DateTime created;

    @LastModifiedDate
    private DateTime modified;

Something to keep in mind: created date is set only when you save document without _id field set.




回答2:


Ok, got it working by using onBeforeConvert instead of onBeforeSave. I was setting the source object and not DBObject. Setting it before convert does the trick.



来源:https://stackoverflow.com/questions/15445592/setting-createdon-and-updatedon-automatically

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!