`
xlofty
  • 浏览: 28388 次
  • 来自: ...
社区版块
存档分类
最新评论

在spring+hibernate下,给hibernate加修改记录

    博客分类:
  • java
阅读更多
使用hibernate的拦截器(Interceptors)
package org.hibernate.test;

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

import org.hibernate.EmptyInterceptor;
import org.hibernate.Transaction;
import org.hibernate.type.Type;

public class AuditInterceptor extends EmptyInterceptor {

    private int updates;
    private int creates;
    private int loads;

    public void onDelete(Object entity,
                         Serializable id,
                         Object[] state,
                         String[] propertyNames,
                         Type[] types) {
        // do nothing
    }

    public boolean onFlushDirty(Object entity,
                                Serializable id,
                                Object[] currentState,
                                Object[] previousState,
                                String[] propertyNames,
                                Type[] types) {

        if ( entity instanceof Auditable ) {
            updates++;
            for ( int i=0; i < propertyNames.length; i++ ) {
                if ( "这里放字段名".equals( propertyNames[i] ) ) {
                    ........currentState[i]是属性值
                    return true;
                }
            }
        }
        return false;
    }

    public boolean onLoad(Object entity,
                          Serializable id,
                          Object[] state,
                          String[] propertyNames,
                          Type[] types) {
        if ( entity instanceof Auditable ) {
            loads++;
        }
        return false;
    }

    public boolean onSave(Object entity,
                          Serializable id,
                          Object[] state,
                          String[] propertyNames,
                          Type[] types) {

        if ( entity instanceof Auditable ) {
            creates++;
            for ( int i=0; i<propertyNames.length; i++ ) {
                if ( "这里放字段名".equals( propertyNames[i] ) ) {
                    ........
                    return true;
                }
            }
        }
        return false;
    }

    public void afterTransactionCompletion(Transaction tx) {
        if ( tx.wasCommitted() ) {
            System.out.println("Creations: " + creates + ", Updates: " + updates, "Loads: " + loads);
        }
        updates=0;
        creates=0;
        loads=0;
    }

}


在sping中配制
<bean id="auditInterceptor" class="org.hibernate.test.AuditInterceptor"/>
<bean id="sessionFactory" class="org.springframework.orm.hibernate.LocalSessionFactoryBean"> 
  <property name="entityInterceptor">
    <ref bean="auditInterceptor"/>
  </property>
</bean>
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics