2010-09-13 57 views
0

我一直在java + maven + spring + hibernate项目中工作,我想在调用saveorupdate之前自动将当前日期分配给POJO。我不介意为所有类的date_created创建new Date(),但它们只是很多。 我刚刚发现春天aop擅长这些事情。
在谷歌上几分钟后,我发现了一个很好的方法来做到这一点。但到目前为止,我看不到我究竟可以如何为POJO指定新的日期,然后实现了我的介绍界面的类。我真的不知道如何把它从我的理解sense.so使这是我怎么会做:如何自动设置date_created使用弹簧aop

//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**/ 
    } 
} 

谁能告诉我我在做什么错在这里还是这只是他错误的方式来实现我想要的?感谢您的阅读

回答

1

如果您使用Hibernate,您可以在将实体监听器保存到数据库之前使用实体监听器来设置该属性。

您只需要一个预留持续侦听程序,将创建日期设置为new Date()

这里是Hibernate documentation on entity listeners

+0

感谢您的阅读!!但是如果它是上次修改后无法在数据库中设置的呢? – 2010-09-13 16:58:25

+0

好的方法,我将不得不为所有的实体做同样的事情。当一切都已经创建并且它们的数量显着时,它们不会非常有用。无论如何感谢 – 2010-09-13 17:07:05

+1

对于上次修改日期,概念是相同的。您只需指定一个预更新侦听器,而不是预留持久侦听器。 – 2010-09-13 17:09:54