black sensei black sensei - 29 days ago 9
Java Question

How to automatically set date_created using spring aop

i've been working on a project in java+maven+spring+hibernate and i wanted to automatically assign the current date to the POJOs before the calling of saveorupdate. i wouldn't mind creating

new Date()
for all the date_created of all the classes but they are just plenty.
I've just discovered that spring aop is good at those things.

After few minutes on google i found a nice way to do it.but up to now i can't see how exactly i can assign new date to POJO which are then implementor classes of my introduction interface.i don't really know how to put it to make sense.so from my understanding this is how i would do:

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


Can anyone show me what i'm doing wrong here?Or this is just he wrong way to achieve what i wanted to do.Thanks for reading

Answer

If you are using Hibernate, you can use entity listeners to set the property before persisting it in the database.

All you need is a pre-persist listener that sets the creation date to new Date().

Here is the Hibernate documentation on entity listeners.