javajpahibernate-entitymanager

setParameter issue with createNativeQuery of entityManager JPA


I want to apply parameter binding to the dynamic native query where the column name which i am fetching i will be passing that dynamically from the UI.(say emp_id in this case).

Following is the sample java code snippet,

org.hibernate.Query queryMain;
String fetchColumn="emp_id";
String query;
query="select e.:id from Employee e";
queryMain = (org.hibernate.Query) em.createNativeQuery(query).unwrap(org.hibernate.Query.class);
queryMain.setParameter("id", fetchColumn);

But when i execute this code i am getting sql syntax error exception. When i print the sql query i am getting as follows

select 'emp_id' from Employee

Since the column was set in string literals it is throwing the sql syntax exception. Can someone help me on this please. Thanks in advance!


Solution

  • As I told you in my comment, the whole point of setParameter is to bind parameter values and prevent SQL injection. You can't use it to pass litterals because they will be surrounded with quotes. To build a query dynamically, you can do something like this:

    StringBuilder sb = new StringBuilder();
    String fetchColumn = "emp_id"; //take care of SQL injection if necessary
    String tableName = Employee.class.getSimpleClassName();
    sb.append("select ").append(fetchColumn)
        .append("from ").append(tableName);
    String query = sb.toString();
    // rest of your code here