je recommande la conception suivante ....
Tout d'abord, vous avez besoin d'un composant LifeCycleInfo ....
Les informations stocke LifeCycleInfo liées lorsque l'instance de modèle persistant a été créé, la dernière modification, supprimé et archivé.
<hibernate-mapping package="com.comp.model">
<class name="Employee" table="employee" lazy="false">
<id name="id">
<generator class="assigned"/>
</id>
<property name="email" type="string" column="email"/>
<!-- Model lifecycle info attributes -->
<component name="LifeCycleInfo" class="com.comp.component.LifeCycleInfo">
<property name="createdDate" type="timestamp" column="created_date"/>
<property name="createdBy" type="string" column="created_by"/>
<property name="lastModifiedDate" type="timestamp" column="last_modified_date"/>
<property name="lastModifiedBy" type="string" column="last_modified_by"/>
<property name="deletedBy" type="string" column="del_by"/>
<property name="deletedDate" type="timestamp" column="del_date"/>
<property name="archivedBy" type="string" column="arc_by"/>
<property name="archivedDate" type="timestamp" column="arc_date"/>
</component>
</class>
Ensuite, vous avez besoin d'une interface de marqueur dire, auditable
public interface Auditable {
Date getCreatedDate();
void setCreatedDate (Date crt_date);
String getCreatedBy();
void setCreatedBy (String user_id);
/* rest of the methods for getting/setting lastModifiedDate/By etc. */
}
Ensuite, votre modèle persistant implémente Auditable
Employee implements Auditable
, vous avez besoin Hibernate Interceptor ...
public class AuditableInterceptor extends EmptyInterceptor {
public boolean onSave(Object entity, Serializable id, Object[] state,
String[] propertyNames, Type[] types)
{
if (entity instanceof Auditable)
{
Date now = new Date();
String userId = factory.getUserName(); /* get user Id from somewhere*/
((Auditable)entity).setCreatedDate(now);
((Auditable)entity).setCreatedBy(userId);
return true;
}
return false;
}
/* rest of the implementation is trivial */
}
Ensuite, enregistrez votre Auditable Interceptor .....
Configuration cfg = new Configuration();
cfg.setInterceptor(new AuditableInterceptor());
.......
/* build SessionFactory */
Vous avez terminé!
EDIT:
Employee.java
...............
public Date getCreatedDate()
{
return this.getLifeCycleInfo().getCreatedDate();
}
public void setCreatedDate(Date createdDate)
{
if (this.getLifeCycleInfo() == null)
this.setLifeCycleInfo(new LifeCycleInfo());
this.getLifeCycleInfo().setCreatedDate(createdDate);
}
....................
Désolé. Je dois utiliser le mapping ORM. Comment fait-on ça? – Jothi
ORM = Mappage relationnel d'objet. Donc, "ORM ne veut rien dire, peut-être que vous voulez dire" cartographie xml "? – Bozho