简体   繁体   English

实体管理器JPA的createNativeQuery出现setParameter问题

[英]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). 我想将参数绑定应用于动态本机查询,其中我正在获取的列名将通过UI动态传递(在这种情况下为emp_id)。

Following is the sample java code snippet, 以下是示例Java代码段,

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. 但是,当我执行此代码时,我得到了sql语法错误异常。 When i print the sql query i am getting as follows 当我打印SQL查询时,我得到如下

select 'emp_id' from Employee

Since the column was set in string literals it is throwing the sql syntax exception. 由于该列是在字符串文字中设置的,因此它将引发sql语法异常。 Can someone help me on this please. 有人可以帮我吗 Thanks in advance! 提前致谢!

As I told you in my comment, the whole point of setParameter is to bind parameter values and prevent SQL injection. 正如我在评论中告诉您的那样, setParameter是绑定参数值并防止SQL注入。 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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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