简体   繁体   English

在 JPA 中使用数组进行本机查询

[英]Native Query with array in JPA

I want to make a query verify value as contained into array in Postgres.我想让查询验证包含在 Postgres 中的数组中的值。 I made a nativeQuery in JPA the query apparently is correct and is working in DBeaver(DBM), but not in java application.我在 JPA 中做了一个 nativeQuery,查询显然是正确的,并且在 DBeaver(DBM)中工作,但在 java 应用程序中没有。

Dbeaver 查询工作 , , 应用程序日志

    ERROR: operator does not exist: integer[] @> character varying
    TIP: No operator matches the name and type of the argument. You need to add explicit type conversions.

AFAIK this is not supported in native queries as they directly delegate to JDBC drivers which do not support it. AFAIK 这在本机查询中不受支持,因为它们直接委托给不支持它的 JDBC 驱动程序。

When you use a JPQL like this:当您使用这样的 JPQL 时:

var query = em.createQuery("select p from Person p where p.name in :names", Person.class);
query.bind("names", List.of("A", "B");

And then check the generated native SQL, then you will see, that the generated SQL looks something like:然后检查生成的原生 SQL,然后你会看到,生成的 SQL 看起来像这样:

select .. from person where person.name in (?, ?)

In your case I am affraid you will have to generate the query dynamically with something like:在您的情况下,我担心您将不得不使用以下内容动态生成查询:

var entries = List.of("A","B");
var sql = new StringBuilder("select ... from person where person.name in (");
for (var i=0; i<entries.size(); i++) {
    sql.append('?');
    if (i<entries.size()-1) sql.append(',');
}
sql.append(')');
var query = em.createNativeQuery(sql.toString());
for (var i=0; i<entries.size(); i++) {
    query.setParameter(i+1, entries.get(i));
}

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

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