views:

77

answers:

1

I wrote a Hibernate interceptor :

public class MyInterceptor extends EmptyInterceptor {

private boolean isCanal=false;

public boolean onSave(Object entity, Serializable arg1, Object[] arg2, String[] arg3, Type[] arg4) throws CallbackException {

 for(int i=0;i<100;i++){
  System.out.println("Inside MyInterceptor(onSave) : "+entity.toString());
 }
 if(entity instanceof Canal){
  isCanal=true;
 }
 return false;
}

public void afterTransactionCompletion(Transaction tx){
 if(tx.wasCommitted()&&(isCanal)){
  for(int i=0;i<100;i++){
   System.out.println("Inside MyInterceptor(afterTransactionCompletion) : Canal was saved to DB.");
  }
 }
}

I can see the method onSave executing fine, but afterTransactionCompletion method never gets executed even though the transaction is successfully commited to the database.

I need a way to track every time a Canal object is successfully saved to the DB and react by printing some messages. is that feasible ? and how ?

Here is the method I use to save objects in the DB :

public static Object enregObjet(Object obj) throws UpdateException,
  EnregException, ErreurException {

Transaction tx = null;
 try {
  Session s = InterfaceBD.currentSession();
  tx = s.beginTransaction();
  try {
   // Positionner les champs dteUti et dteUtiModif
   Method dteUtiSetter = null;
   ;
   // Objet en insertion
   dteUtiSetter = obj.getClass().getMethod("setDteUti",
     new Class[] { java.util.Date.class });
   dteUtiSetter.invoke(obj, new Object[] { new java.util.Date() });
  } catch (NoSuchMethodException ex) {
   ;// Le champ dteUtiModif n'existe pas
  }
  // Enregistrer
  IardNum.numeroterCode(obj);
  IardNum.numeroterId(obj);
  s.save(obj);
  s.flush();
  tx.commit();
  try {
   String id = "";
   // Positionner les champs dteUti et dteUtiModif
   Method idGetter = null;
   // Objet en insertion
   idGetter = obj.getClass().getMethod("getId");
   id = (String) idGetter.invoke(obj);
   Connection conn = InterfaceBD.getConn();
   IardGenerator3.cleanSeq(id, conn);
   conn.close();
  } catch (NoSuchMethodException ex) {
   ;// Le champ dteUtiModif n'existe pas
  }
  catch(ClassCastException ex){
   ;//just ignore it because we are dealing with a PK class (e.g : CausesAnnexesSinistrePK).
  }
  s.clear();
  return obj;
}
A: 

I would suggest using DAO design template. Basicaly you just create an class, which will save Canal object and use it everywhere where you need to save it. In this class you can add all logic you need.

Artem