java - 如何使用spring aop自动设置date_created

标签 java spring hibernate spring-aop

我一直在 java+maven+spring+hibernate 中开发一个项目,我想在调用 saveorupdate 之前自动将当前日期分配给 POJO。我不介意为所有类的所有 date_created 创建 new Date() ,但它们已经足够了。 我刚刚发现 spring aop 擅长这些事情。
在谷歌上几分钟后,我找到了一个很好的方法。但是到目前为止,我不知道如何准确地将新日期分配给 POJO,然后 POJO 是我的介绍接口(interface)的实现类。我真的不知道如何让它有意义。所以根据我的理解,这就是我会做的:

//DateSetter.java
package org.personal.myproject.model;

import java.util.Date;
//this is how i'm getting the current date
public interface DateSetter {

   public Date getCurrentDate();

}


//DateCreatedDateSetterImpl.java
package org.personal.myproject.model;

import java.util.Date;
// the implementation
public class DateCreatedDateSetterImpl implements DateSetter {

  public Date getCurrentDate() {
    return new Date();
  }

}

//DateIntroduction.java
package org.personal.myproject.model;

import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.DeclareParents;

@Aspect
public class DateIntroduction {
    //making all the model implementors of the DateSetter interface
    @DeclareParents(value="org.personal.myproject.model.*",
    defaultImpl=DateCreatedDateSetterImpll.class)
    public DateSetter dateSetter;

    /**here is to add my "before trigger" for every calling of every method.
       if you can see i have the daos in 2 packages, i don't know whether is wrong or         not.i'm actually using the generic Dao so should i use that interface instead?
    **/
    @Before("execution * org.personal.myproject.dao.hibernate.*.(..) || *    org.personal.myproject.dao.hibernate.*.*.(..)" + "&& this(dateSetter)")
    public void injectLastModifiedDate(DateSetter dateSetter){
      /**so here i'm expecting to inject the new date but apparently i'm missing something**/
    }
}

任何人都可以告诉我我在这里做错了什么吗?或者这只是他实现我想做的事情的错误方法。感谢您的阅读

最佳答案

如果您使用 Hibernate,则可以使用实体监听器来设置属性,然后再将其保留在数据库中。

您所需要的只是一个将创建日期设置为 new Date() 的预持久监听器。

这是Hibernate documentation on entity listeners .

关于java - 如何使用spring aop自动设置date_created,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3702568/

相关文章:

java - 来自字母数字字符串的与语言无关的随机数生成器

java - Spring Web App - 由 Java.lang.ClassNotFoundException 引起的 CannotLoadBeanClassException

javascript - <html :hidden> and &lt;input type ="hidden"> on IE11 之间的区别

spring - 将正则表达式数组传递给基于 spring 的 mongo @Query

java - 从 hibernate 中获取查询的执行时间

java - @Value注解不起作用

java - tomcat运行时NoSuchMethodError如何解决?

java - 使用唯一的字符串设置默认适配器

java - 如何在我的 jsp 中使用 javascript 访问来自服务器的 java 列表

java - hibernate 性能不佳