Developer
Developer

Reputation: 1813

Passing Class name a a parameter in Hibernate named Queries

I'm using Hibernate to read data from database I used the following named query:

<query name="getTable">
    select tbl from ? as tbl order by col
    </query>

In the DAO

public List<Object> selectTables(String className){

           Query query = session.getNamedQuery("getTable");
           query.setParameter(0, className);
           return (List<Object>)query.list();
    }

When I run the code, I get the following exception

14:13:57,463 ERROR SessionFactoryImpl:405 - Error in named query: getTable
org.hibernate.hql.ast.QuerySyntaxException: unexpected token: ? near line 2, column 25 [
    select tbl from ? as tbl order by col

    ]

Upvotes: 3

Views: 1617

Answers (2)

Bernardo J. Rios
Bernardo J. Rios

Reputation: 11

Try to replace Query for Criteria.

     public List<Object> selectTables(Class className){
           Criteria criteria = session.createCriteria(className);
           return (List<Object>)criteria.list();
     }

Upvotes: 0

JB Nizet
JB Nizet

Reputation: 692121

You can't do that. The placeholders (?) are not just replaced by Hibernate by any parameter you might pass. The HQL query is translated to a SQL prepared statement, and the placeholders are parameters of this prepared statement.

A prepared statement is used by the database to compute the execution plan for the query. So if the query doesn't even contain the table name, it's impossible to compute the execution plan. You can only pass values as parameters to a query. You can't pass column names or table names.

Upvotes: 3

Related Questions