Çağdaş Salur
Çağdaş Salur

Reputation: 1390

Can Spring Hibernate interecpt queries?

I am developing an application where i need to intercept all sql queries made, and add something like "WHERE customer_id={id}" after every query so don't have to add the clause every time i use a query.

Is there a way to filter every query before it's sent to the database?

Upvotes: 0

Views: 59

Answers (1)

Angad Bansode
Angad Bansode

Reputation: 923

Yes, hibernate provide class EmptyInterceptor, We have to extend this class and overrides all methods. Before going to this step we have to register our interceptor to hibernate session.

 // 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) Register our LoggingInterceptor with hibernate session for monitor all operations.

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

}

Upvotes: 3

Related Questions