tags:

views:

68

answers:

2

I have to find out if there are entries in a table that also exist in a list I have in Java. The logical solution would be "SELECT column FROM table WHERE column IN (?)" and then set ? to the array I have in Java, but setArray asks for a java.sql.Array and I'm not really sure how to obtain one and if it really is what I am looking for.

+3  A: 

No, that's not possible.

Unfortunately, IN requires two steps:

  1. Add one binding ? for each value.
  2. Loop over the values and bind them to the ?

No easy way to do it.

duffymo
I'd ask everyone who downvotes my answer to try the jGuru solution and see if it really works. If it fails, come back and up vote mine.
duffymo
Yes please, if the jGuru method fails or is notapplicable here, I'll delete my answer. Can't test it myself, unfortunately.
Andreas_D
You're right, this is the only way.
Henning
This is the only way. I'll test it tonight to prove it.
duffymo
+1  A: 

You can't do this with JDBC but if are using spring or hibernate, both have support for rewriting a query to unroll a list of parameters into the right number of ?.

Query query = session.createQuery("select x from y where z in (:params)");
query.setParameterList("params", paramList);
List list = query.list();

In spring you need to use the NamedParameterJdbcTemplate.

Mike Q
Nope, Spring won't do it, either.
duffymo
@duffymo: Spring does: http://static.springsource.org/spring/docs/3.0.x/spring-framework-reference/html/jdbc.html#jdbc-in-clause
axtavt
Thank you for the correction axtavt - I haven't digested Spring 3.x yet.
duffymo
I'd wonder if you looked at the Spring 3.x source code that it'd be doing exactly what I suggested. Spring is just "syntactic sugar" in this case; it can only be done easily if the JDBC driver supports it. Has there been a change to JDBC to make this possible?
duffymo
@duffymo: Spring is rewriting the query. The NamedParamJdbcTemplate supports hibernate style named parameters (:params) which it rewrites to ? internally. Much like hibernate it can detect that a parameter is actually a Collection/array and unroll :params -> (?, ?, ? ... ?) JDBC has no support for this, tho it would be nice.
Mike Q
Correct - "rewrites internally". So it's not possible to do it without unrolling.
duffymo