在Hibernate拦截器中使用postFlush方法的错误

时间:2016-11-24 13:32:52

标签: java spring hibernate interceptor

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

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

@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();
}

在Registry中我存储有关在我正在检查的表上执行的操作的信息。

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

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

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

我尝试的最后一件事是以一种非常“肮脏”的方式。我改变了我的代码:

@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);
}

它有效!我能够存储人员和登记处的信息,但这不是正确的方式吗?

提前致谢

1 个答案:

答案 0 :(得分:1)

我以这种方式审核,但日期很难看。

的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 = "";
            }
        }
    }

}