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

8aqjt8rx  于 2023-08-06  发布在  其他
关注(0)|答案(4)|浏览(102)

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

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查询中?
我使用EclipseLink 2.5.0和MySQL服务器5.6.13
谢啦,谢啦

q3qa4bjr

q3qa4bjr1#

我相信你只能为JPQL查询设置列表参数,而不是原生查询。
要么使用JPQL,要么用列表动态地构造SQL。

oyjwcjzk

oyjwcjzk2#

如果将参数命名为:

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);

字符串

nxowjjhe

nxowjjhe3#

不是一个解决方案,而是一个解决方案。

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 );

字符串

8e2ybdfx

8e2ybdfx4#

您可以添加多个值,如下例所示:

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

相关问题