Hibernate 拦截器中的方法 post Flush 出错

Errror with method postFlush in Hibernate Interceptors

我想在我的数据库中记录在 table 上执行的操作(插入、更新和删除)。我一直在阅读有关拦截器的信息,所以我实现了自己的拦截器。

例如,当执行插入时,我这样做:

@Override
public boolean onSave(Object entity, Serializable id, Object[] state, String[] propertyNames, Type[] types) {
    if (entity instanceof Person) {
        System.out.println("Se ha insertado una persona");
        operation = "Insert";
        date = Calendar.getInstance().getTime();
        return true;
    }
    return false;
}

最后在 postFlush 中我这样做了:

// called after committed into database
public void postFlush() {
    System.out.println("postFlush");
    Session ses = HibernateUtil.getSessionFactory().openSession();
    ses.getTransaction().begin();
    Registry reg = new Registry(operation, date);
    ses.save(reg);
    ses.getTransaction().commit();
}

在注册表中,我存储了有关在我正在检查的 table 上执行的操作的信息。

我在使用保存、更新和删除方法调用 class 上的拦截器时遇到了很多问题。在网上和这里(我喜欢这个网站 jeje)阅读了几个小时后,我能够以这种方式调用拦截器:

    Session session = this.sessionFactory.withOptions().interceptor(new MyInterceptor).openSession();

我 运行 我的简单网络应用程序可以保存一个人的姓名和国家/地区。我能够存储此人的信息,但我的注册表 table 是空的。我调试了我的代码,但从未调用过 postFlush 方法。有任何想法吗?我遵循了各种教程和一些建议,但似乎没有任何效果。

我尝试的最后一件事是非常 "dirty" 的方式。我改变了我的代码:

@Override
@Transactional
public void addPerson(Person p) {
    Session session = this.sessionFactory.withOptions().interceptor(new MyInterceptor).openSession();
    session.save(p);
    logger.info("Person saved successfully, Person Details="+p);
}

以这种(可怕的)方式:

@Override
@Transactional
public void addPerson(Person p) {
    MyInterceptor m = new MyInterceptor();
    Session session = this.sessionFactory.withOptions().interceptor(m).openSession();
    Transaction tx = session.beginTransaction();
    session.save(p);
    tx.commit();
    session.flush();
    m.postFlush();
    logger.info("Person saved successfully, Person Details="+p);
}

而且成功了!我能够存储人员信息以及注册表中的信息,但这不是正确的方法吗?

提前致谢

我是这样审核的,但是日期很丑..

persistence.xml

<property name="hibernate.ejb.interceptor" value="siapen.jpa.interceptor.MeuInterceptador" />

java代码

import java.io.Serializable;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Iterator;

import org.apache.commons.lang3.ObjectUtils;
import org.hibernate.CallbackException;
import org.hibernate.EmptyInterceptor;
import org.hibernate.type.Type;

import siapen.model.BaseEntity;

public class MeuInterceptador extends EmptyInterceptor {

    private static final long serialVersionUID = 7853236444153436270L;

    private String strSQL = "";
    String acao;
    @SuppressWarnings("rawtypes")
    BaseEntity entity;
    String s = "";

    @SuppressWarnings("unchecked")
    // 1
    public boolean onSave(Object obj, Serializable id, Object[] valores, String[] propertyNames, Type[] types)
            throws CallbackException {
        if (obj instanceof BaseEntity) {
            entity = (BaseEntity) obj;
            for (int i = 0; i < valores.length; i++) {
                if (valores[i] != null && !valores[i].equals("")) {
                    s += propertyNames[i] + ":" + valores[i];
                    if (i != valores.length - 1) {
                        s += "___";
                    }
                }
            }
        }
        return false;
    }

    @SuppressWarnings("unchecked")
    // 1
    public boolean onFlushDirty(Object obj, Serializable id, Object[] valoresAtuais, Object[] valoresAnteriores,
            String[] propertyNames, Type[] types) throws CallbackException {
        if (obj instanceof BaseEntity) {
            entity = (BaseEntity) obj;

            for (int i = 0; i < valoresAtuais.length; i++) {

                if (!ObjectUtils.equals(valoresAtuais[i], valoresAnteriores[i])) {
                    if (!s.equals("")) {
                        s += "___";
                    }
                    s += propertyNames[i] + "-Anterior:" + valoresAnteriores[i] + ">>>Novo:" + valoresAtuais[i];
                }
            }
        }
        return false;

    }

    @SuppressWarnings("unchecked")
    // 1
    public void onDelete(Object obj, Serializable id, Object[] state, String[] propertyNames, Type[] types) {
        if (obj instanceof BaseEntity) {
            entity = (BaseEntity) obj;
        }
    }

    // CHAMADO ANTES DO COMMIT
    // 2
    @SuppressWarnings("rawtypes")
    public void preFlush(Iterator iterator) {
    }

    // 3
    public String onPrepareStatement(String sql) {
        acao = "";
        if (sql.startsWith("/* update")) {
            acao = "update";
        } else if (sql.startsWith("/* insert")) {
            acao = "insert";
        } else if (sql.startsWith("/* delete")) {
            acao = "delete";
        }
        if (acao != null) {
            strSQL = sql;
        }
        return sql;
    }

    // CHAMADO APÓS O COMMIT
    // 4
    @SuppressWarnings("rawtypes")
    public void postFlush(Iterator iterator) {
        if (acao != null) {
            try {
                if (acao.equals("insert")) {
                    AuditLogUtil audi = new AuditLogUtil();
                    audi.LogIt("Salvo", entity, s);
                }
                if (acao.equals("update")) {
                    AuditLogUtil audi = new AuditLogUtil();
                    audi.LogIt("Atualizado", entity, s);
                }
                if (acao.equals("delete")) {
                    AuditLogUtil audi = new AuditLogUtil();
                    audi.LogIt("Deletado", entity, "");
                }

            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                strSQL = "";
                s = "";
            }
        }
    }

}