简体   繁体   中英

Native Query with array in JPA

I want to make a query verify value as contained into array in Postgres. I made a nativeQuery in JPA the query apparently is correct and is working in DBeaver(DBM), but not in java application.

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.

When you use a JPQL like this:

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:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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