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

后端 未结 2 825
既然无缘
既然无缘 2021-01-24 21:10

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,         


        
相关标签:
2条回答
  • 2021-01-24 21:46

    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.

    0 讨论(0)
  • 2021-01-24 21:52

    If your goal is to add an extra column with a constant value, try giving it an alias:

    SELECT a, b, c, "TESTVALUE" AS `new_column` FROM ...
    
    0 讨论(0)
提交回复
热议问题