简体   繁体   中英

Jdbc template named parameters for querying with IN clause

I need to copy the records of one table to another table based on some condition.

String query = "insert into public.ticket_booking_archive select * from public.ticket_booking where ticketId in (:ticketIds)";

So here the :ticketIds are dynamic, where i need to pass ticketIds to make sure whether it satisfies the condition. So it may be the matching and non matching ticket id's here at runtime.

The values of ticketIds are something like this ('f1fa3a42-5837-11ec-bf63-0242ac130002','516fd14d-3c9d-4b4b-91a0-b684d8592dfe','c9652f86-734c-4df5-8ef9-d407cb3eaf7a','df7f2812-b445-45b4-b731-da23c36d7738','f1fa3a42-5837-11ec-bf63-0242ac130002') . And this is just an example. And the list might goes on.

Since it is of type UUID, I'm storing it into a Set<UUID>

Set<UUID> tktIds = new HashSet<UUID>();

for(int i=0 ; i<ticketIds.size(); i++) {
String ticketId = ticketIds[i];
tktIds.add(UUID.fromString(ticketId));
}

Map<String, Object> params = new HashMap<>();
params.put("ticketIds", tktIds);

SqlParameterSource namedParameters =
                 new MapSqlParameterSource().addValue("ticketIds",params.get("ticketIds"));

Since I'm using NamedParameterJdbcTemplate, so I'm using like below

int res = writeNamedJdbcTemplate.update(query, namedParameters);

res = 3 when executed programmatically.

Here the problem is, as soon as it finds the first matching value in the IN clause it executes. And it is not considering the other matching values (ticketIds here)

But if I execute the same query in pgadmin it works fine

insert into public.ticket_booking_archive select * from public.ticket_booking where ticketId in ('f1fa3a42-5837-11ec-bf63-0242ac130002','516fd14d-3c9d-4b4b-91a0-b684d8592dfe','c9652f86-734c-4df5-8ef9-d407cb3eaf7a','df7f2812-b445-45b4-b731-da23c36d7738','f1fa3a42-5837-11ec-bf63-0242ac130002');

result is 6. Working as expected.

writeNamedJdbcTemplate.queryForObject(query, namedParameters, Integer.class); //. throws an error

Can anyone please assist? I'm really not sure where I'm making a mistake

I am not quite sure whether you are using the appropriate JDBC template for the named parameters, but you can do the following:

  1. you can consult this article to use the right template and employ proper SQL query composition,

  2. for string passing you can wrap the parameter mapping as shown here

after all your named parameter should work

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