将列表参数设置为本机查询

时间:2013-09-09 15:37:28

标签: java sql jpa nativequery

我想将参数设置为本机查询

javax.persistence.EntityManager.createNativeQuery

像这样的东西

Query query = em.createNativeQuery("SELECT * FROM TABLE_A a WHERE a.name IN ?");
List<String> paramList = new ArrayList<String>();
paramList.add("firstValue");
paramList.add("secondValue");
query.setParameter(1, paramList);

在异常中尝试此查询结果:

Caused by: org.eclipse.persistence.exceptions.DatabaseException:
Internal Exception: com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException:
You have  an error in your SQL syntax; check the manual that corresponds to your MySQL server 
version for the right syntax to use near
'_binary'??\0♣sr\0‼java.util.ArrayListx??↔??a?♥\0☺I\0♦sizexp\0\0\0☻w♦\0\0\0t\0
f' at line 1
Error Code: 1064
Call: SELECT * FROM Client a WHERE a.name IN ?
        bind => [[firstValue, secondValue]]
Query: ReadAllQuery(referenceClass=TABLE_A sql="SELECT * FROM TABLE_A a WHERE a.name IN ?")

是否可以为本机查询设置list参数,而不是强制转换为字符串并将其附加到sql查询?

P.S。我使用EclipseLink 2.5.0和MySQL服务器5.6.13

由于

3 个答案:

答案 0 :(得分:3)

我相信你只能为JPQL查询设置列表参数,而不是本机查询。

使用JPQL,或使用列表动态构造SQL。

答案 1 :(得分:1)

不是解决方案,而是更多的解决方法。

 Query query = em.createNativeQuery("SELECT * FROM TABLE_A a WHERE a.name IN ?");
    List<String> paramList = new ArrayList<String>();
    String queryParams = null;
    paramList.add("firstValue");
    paramList.add("secondValue");
    query.setParameter(1, paramList);

    Iterator<String> iter = paramList.iterator();
int i =0;

while(iter.hasNext(){
    if(i != paramList.size()){

    queryParams = queryParams+ iter.next() + ","; 

    }else{

    queryParams = queryParams+ iter.next();

   }
   i++;
}

query.setParameter(1, queryParams );

答案 2 :(得分:0)

如果您命名参数,它将起作用:

Query query = em.createNativeQuery("SELECT * FROM TABLE_A a WHERE a.name IN (:names)");
List<String> paramList = new ArrayList<String>();
paramList.add("firstValue");
paramList.add("secondValue");
query.setParameter("names", paramList);