spring可以休眠interecpt查询吗?

2w2cym1i  于 2021-06-23  发布在  Mysql
关注(0)|答案(1)|浏览(230)

我正在开发一个应用程序,在其中我需要截取所有sql查询,并在每个查询之后添加类似“where customer\u id={id}”的内容,这样就不必在每次使用查询时都添加子句。
有没有办法在每个查询发送到数据库之前进行过滤?

afdcj2ne

afdcj2ne1#

是的,hibernate提供类emptyinterceptor,我们必须扩展这个类并重写所有方法。在执行此步骤之前,我们必须注册拦截器以休眠会话。

// Logging Interceptor..
public class LoggingInterceptor extends EmptyInterceptor {

   private static final long serialVersionUID = 1L;
   // Define a static logger
   private static Logger logger = LogManager.getLogger(LoggingInterceptor.class);

    // 1) save
   @Override
   public boolean onSave(Object entity, Serializable id, Object[] state,
            String[] propertyNames, Type[] types) 
   {
      logger.info("onSave method is called.");
      System.out.println("LoggingInterceptor . onSave() before save this method is called.");
      if (entity instanceof Book) {
         Book book = (Book) entity;
         logger.info(book.toString());
      }
      return super.onSave(entity, id, state, propertyNames, types);
   }

2) 在hibernate会话中注册我们的logginginterceptor以监视所有操作。

public class MainApp {

   public static void main(String[] args) {

      Session session = null;
      Transaction transaction = null;
      try {
         session = HibernateUtil.getSessionFactory()
               .withOptions()
               .interceptor(new LoggingInterceptor()) // add Logging_interceptor to Session
               .openSession();

         transaction = session.getTransaction();
         transaction.begin();

}

相关问题