10

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

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 ?")

有没有办法为本地查询设置列表参数,而不是转换为字符串并将其附加到 sql 查询?

PS 我使用的是 EclipseLink 2.5.0 和 MySQL 服务器 5.6.13

谢谢

4

4 回答 4

3

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

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

于 2013-09-10T14:41:42.010 回答
2

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

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);
于 2019-04-10T09:08:46.753 回答
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 );
于 2016-11-18T18:25:44.513 回答
0

您可以像以下示例一样添加多个值:

TypedQuery<Employee> query = entityManager.createQuery(
"SELECT e FROM Employee e WHERE e.empNumber IN (?1)" , Employee.class);
List<String> empNumbers = Arrays.asList("A123", "A124");
List<Employee> employees = query.setParameter(1, empNumbers).getResultList();

资料来源:PRAGT E.,2020。JPA查询参数用法。取自:https ://www.baeldung.com/jpa-query-parameters

于 2022-02-22T12:49:19.543 回答