简体   繁体   中英

why IN clause not supported in with getEntityManager().createNativeQuery

I am using eclipse link as JPA and Oracle as DB. I am using getEntityManager().createNativeQuery in java. In my query I want to use IN clause but it is not working and no exception as well.

From page user passes the input as 336885,56239,895423

Sample Query

"select emp_name from emp where emp_id in ( ?id)"    

query.setParameter("id", empBO.getEventIds());

I am using Java to convert the using split and concat

336885,56239,895423 to '336885','56239','895423'

but it is not working out for me.

I knew if we use JPQL this going to work for me. the reason behind choosing Native is to avoid creating Model objects for tables.

Update

I have used JPQL query since I need to deliver the code quickly. I have tried second answer what posted here. But no result came. when I get a free time I will try once again why IN is not working.

The reason why this wouldn't work with JPA is the same why this wouldn't work directly with JDBC - it is lack of support in JDBC of multi-valued parameters.

When JPQL processor sees in (?id) it converts it into an expression that its underlying SQL engine could "understand" - usually, something that looks like this:

WHERE  emp_id IN (?id_0, ?id_1, ?id_2, ...)

This is supported by JDBC, so it executes without an error.

If you would like to perform a native query, you need to do this conversion yourself. Start with the template that you have, insert question marks for the number of IDs that you are sending, and bind IDs from the list to these parameters:

StringBuilder queryStr = new StringBuilder("select emp_name from emp where emp_id in (");
int[] ids = empBO.getEventIds();
for (int i = 0 ; i != ids.length() ; i++) {
    queryStr.append("?id_");
    queryStr.append(i);
}
queryStr.append(")");
... // Construct your query, then...
for (int i = 0 ; i != ids.length() ; i++) {
    query.setParameter("id_"+i, ids[i]);
}

You can show the log of jpa to see the request in you code.

log4j.logger.org.hibernate=info<BR>

or

<logger name="org.hibernate"><BR>
  <level value="info"/> <BR>
</logger><BR>

You can also try without parenthese :
"select emp_name from emp where emp_id in ?id"

Are you sure for ? ?

"select emp_name from emp where emp_id in :id"

Regards,

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