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

牧云@^-^@ 提交于 2019-12-02 08:09:15

问题


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


回答1:


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.




回答2:


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 ...


来源:https://stackoverflow.com/questions/26718200/add-a-column-to-all-mysql-select-queries-in-a-single-shot

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!