Search code examples
javamysqlhibernatedialect

Add a column to all MySQL Select Queries in a single shot


Trying to add a comment to all MySQL Select Queries in my web application at runtime.

For example, the original queries in the code looks like:

select a,b,c from ......
select x,y from...

All of these need to be modified at runtime to:

select a,b,c /*Comment*/ from ...
select x,y /*Comment*/ from ...

The application runs on Hibernate 4.2.1. Only solution I can think of is extending the org.hibernate.dialect.MySQLDialect and add the /*Comment*/ in the new CustomMySQLDialect.

A little confused on which method to modify to accomplish this. Would appreciate any pointer in the right direction.

Can transformSelectString(java.lang.String) method in org.hibernate.dialect.Dialect be overridden to accomplish this?

EDIT 1: transformSelectString in a Custom MySQL Dialect is not working for runtime SQL modification


Solution

  • Create a Custom DB Interceptor

    package com.felix.dao.interceptor;
    import org.hibernate.EmptyInterceptor;
    
    public class CustomDBInterceptor extends EmptyInterceptor {
    
      @Override
      public String onPrepareStatement(String sql) {
        String commentStr = "/*Comment*/"
        return super.onPrepareStatement(commentStr+sql);
      }
    
    }
    

    In the Spring Context file, configure the Interceptor for the session factory:

    <bean id="customDBInterceptor" class="com.felix.dao.interceptor.CustomDBInterceptor"/>
    <bean id="sessionFactory"
        class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
        <property name="dataSource" ref="datasource" />
        <property name="entityInterceptor">
            <ref bean="customDBInterceptor"/>
        </property>
        ...
    </bean>
    

    Make sure the Custom DB Interceptor does not have a cyclic dependency on the sessionFactory. With the above, all queries fired through the session factory, are intercepted, modified and then passed to the onPrepareStatement method.