2010-09-13 59 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