Hibernate拦截器

来源:互联网 发布:淘宝网店工作室怎么开 编辑:程序博客网 时间:2024/05/06 00:19

原文地址:http://docs.jboss.org/hibernate/orm/5.2/userguide/html_single/Hibernate_User_Guide.html#events-interceptors

The org.hibernate.Interceptor interface provides callbacks from the session to the application, allowing the application to inspect and/or manipulate properties of a persistent object before it is saved, updated, deleted or loaded.

One possible use for this is to track auditing information. The following example shows an Interceptor implementation that automatically logs when an entity is updated.

public static class LoggingInterceptor extends EmptyInterceptor {    @Override    public boolean onFlushDirty(        Object entity,        Serializable id,        Object[] currentState,        Object[] previousState,        String[] propertyNames,        Type[] types) {            LOGGER.debugv( "Entity {0}#{1} changed from {2} to {3}",                entity.getClass().getSimpleName(),                id,                Arrays.toString( previousState ),                Arrays.toString( currentState )            );            return super.onFlushDirty( entity, id, currentState,previousState, propertyNames, types);    }}

You can either implement Interceptor directly or extend org.hibernate.EmptyInterceptor.

An Interceptor can be either Session-scoped or SessionFactory-scoped.

A Session-scoped interceptor is specified when a session is opened.

SessionFactory sessionFactory = entityManagerFactory.unwrap( SessionFactory.class );Session session = sessionFactory    .withOptions()    .interceptor(new LoggingInterceptor() )    .openSession();session.getTransaction().begin();Customer customer = session.get( Customer.class, customerId );customer.setName( "Mr. John Doe" );//Entity Customer#1 changed from [John Doe, 0] to [Mr. John Doe, 0]session.getTransaction().commit();

SessionFactory-scoped interceptor is registered with the Configuration object prior to building the SessionFactory. Unless a session is opened explicitly specifying the interceptor to use, the SessionFactory-scoped interceptor will be applied to all sessions opened from that SessionFactorySessionFactory-scoped interceptors must be thread safe. Ensure that you do not store session-specific states since multiple sessions will use this interceptor potentially concurrently.

SessionFactory sessionFactory = new MetadataSources( new StandardServiceRegistryBuilder().build() )    .addAnnotatedClass( Customer.class )    .getMetadataBuilder()    .build()    .getSessionFactoryBuilder()    .applyInterceptor( new LoggingInterceptor() )    .build();

0 0
原创粉丝点击