【发布时间】:2009-11-09 15:36:39
【问题描述】:
我写了一个Hibernate拦截器:
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.");
}
}
}
我可以看到 onSave 方法执行得很好,但是即使事务成功提交到数据库,afterTransactionCompletion 方法也永远不会执行。
我需要一种方法来跟踪每次成功将 Canal 对象保存到数据库并通过打印一些消息来做出反应。那可行吗?以及如何?
这是我在数据库中保存对象的方法:
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;
}
【问题讨论】:
-
是否配置了 TransactionManager?您在哪个容器中运行它?
-
我编辑了我的问题。我发布了用于在数据库中插入对象的方法。我从会话 bean 中插入对象。
标签: java hibernate jakarta-ee