Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to add table name as one of the parameters of the hibernate template query

Obviously, the hibernate template query injects the string parameter "tableName" into the query with quotes. Which will cause SQL grammar syntax errors.

How to add the table name as one of the query params?

For example, the following code will not work because of the table name:

SQLQuery query = session.createSQLQuery("SELECT ID FROM :tableName");
query.setFlushMode(FlushMode.MANUAL);
query.setReadOnly(true);
query.setParameter("tableName", "STUDENT");
List<Object[]> list = query.list();
like image 502
Q i Avatar asked Jul 01 '15 08:07

Q i


1 Answers

Table names cannot be parametrized in queries.

What you actually want to achieve is to build a String which will be used to construct the query:

SQLQuery query = session.createSQLQuery(getIdsQuery("STUDENT"));
...
private String getIdsQuery(String tableName) {
   return "SELECT ID FROM " + tableName;
}

The lack of the ability to parametrize table names has nothing to do with Hibernate - the databases don't support it. And it would make no sense to support it.

The bind variables exist primarily for performance reasons. The point is that you send a query to the database (via jdbc driver) with the placeholders for variables that will change between the invocations of the same query:

select id from STUDENT where name = ?

The database will parse this query, calculate the cost for it, make an execution plan and cache it. The subsequent invocations of the query will be much faster, because all of these steps are skipped and the cached execution plan is used.

How could the database cache the statement and the execution plan if the table name is unknown (parametrized)? It would not know the cost and optimal path to fetch the data if it does not know where to fetch the data from.

Also, the database would not be able to completely validate the query when parsing it if it does not know whether the referenced columns actually exist in the table (which would be unknown at statement parse time if the table names were parametrized).

like image 180
Dragan Bozanovic Avatar answered Oct 03 '22 08:10

Dragan Bozanovic