简体   繁体   中英

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

    ]

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.

Try to replace Query for Criteria.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM