The custom interceptor needs to implement the Interceptor interface. The interceptor is also designed using the observer pattern. The methods in the Interceptor are rewritten. Under certain conditions, these methods will be called.
In the methods of the Interceptor object, you cannot directly use the Session object to perform persistence operations. If you need to use the Session object to complete the persistence while intercepting, you can use the event listener in Hibernate.
The following is an example of an interceptor, which saves the addition, deletion, and modification information of data to the log file, which uses log4j.
Write a custom interceptor LogInterceptor.java:
1 public class LogInterceptor extends EmptyInterceptor { 2 // Process the logs of the LogInterceptor class 3 private Logger logger = Logger.getLogger(LogInterceptor.class ) ; 4 5 @Override 6 public boolean onSave(Object entity, Serializable id, Object[] state, 7 String[] propertyNames, Type[] types) { 8 logger.info("Save data" ); 9 // If the state of the persistent object is modified, return true; otherwise return false 10 return false ; 11 } 12 13 @Override 14 public void onDelete(Object entity, Serializable id, Object[] state, 15 String[] propertyNames, Type[] types) { 16 logger.info("Delete data" ); 17 } 18 19 @Override 20 public boolean onFlushDirty(Object entity, Serializable id, 21 Object[] currentState, Object[] previousState, 22 String[] propertyNames, Type[] types) { 23 logger.info("Modify data" ); 24 // If modified persistent The state of the object, return true; otherwise return false 25 return false; 26 } 27 }
The interceptor can be loaded before parsing the configuration file, or when the session is opened:
Load before parsing the config file config file:
1 static { 2 Configuration cfg = null ; 3 // Parse the configuration file 4 try { 5 cfg = new Configuration(); 6 // Load the filter when parsing the configuration file 7 cfg.setInterceptor( new LogInterceptor()); 8 cfg .configure(); 9 } 10 catch (Exception e) { 11 e.printStackTrace(); 12 } 13 factory = cfg.buildSessionFactory(); 14 }
Load when opening the session:
1 Configuration cfg = new Configuration(); 2 cfg.configure(); 3 SessionFactory factory = cfg.buildSessionFactory(); 4 Session session = factory.openSession(new LogInterceptor()); 5 Transaction ts = session.beginTransaction();
Note: The interceptor is loaded when the session is opened. This interceptor is only valid in the current session.
Configure log4j.properties:
log4j.rootLogger=info,appender1,appender2
log4j.appender.appender1=org.apache.log4j.ConsoleAppender
log4j.appender.appender1.layout=org.apache.log4j.PatternLayout
log4j.appender.appender1.layout.ConversionPattern=[%d{yy/MM/dd HH:mm:ss:SSS}][%c] %m%n
log4j.appender.appender2=org.apache.log4j.FileAppender
log4j.appender.appender2.layout=org.apache.log4j.PatternLayout
log4j.appender.appender2.layout.ConversionPattern=[%d{HH:mm:ss}][%c] %m%n
log4j.appender.appender2.File=HongtenLog4j.log