Can Spring Hibernate interecpt queries?

The name of the pictureThe name of the pictureThe name of the pictureClash Royale CLAN TAG#URR8PPP



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?




1 Answer
1



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







By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

Popular posts from this blog

Firebase Auth - with Email and Password - Check user already registered

Dynamically update html content plain JS

Creating a leaderboard in HTML/JS