0% found this document useful (0 votes)
21 views5 pages

X 3

Spring
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF or read online on Scribd
0% found this document useful (0 votes)
21 views5 pages

X 3

Spring
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF or read online on Scribd
You are on page 1/ 5
03112023 20:31 Using a List of Values ina JabeTemplate IN Clause | Baeldung “ Using a List of Values in a JdbcTemplate IN Clause thttos //adsfreestarcom/? | writen by: Gang wu htos:/winbaeldung.com/author/gangw) Spring Data (https://www.baeldung.com/category/persistence/spring-persistence/spring-data) JDBC ihttps://www.bacldung.com/tag/jdbe) SOL (https://wwwbaeldung.com/tag/sq) Get started with Spring Data JPA through the reference Learn Spring Data JPA course: >> CHECK OUT THE COURSE (/learn-spring-data-jpa-course) y (https//ads freestarcom/? Lutm_campaign-branding&iutm .medium-banner&iutm source-baeldung.com&utm.content-baeldung.incontent 2 1. Introduction Ina SOL statement, we can use the IN operator to test whether an expression matches any value ina list. As such, \we can use the IN operator instead of multiple OR conditions, In this tutorial, wel learn how to passa list of values into the IN clause of a Spring JDBC template (/spring-idbc- jdbctemplate) query. - v hitps:vww-baeldung.com/springjdbclemplate-nist 8 03112023 20:31 Using a List of Values ina JabeTemplate IN Clause | Baeldung 2. Passi~¢ a [.ist Parameter to /NClause The IN operator allows us to specify multiple values in a WHERE clause. For example, we can use it to find all ‘employees whose id isin a specified id ist SELECT» FRO PLOVEE WERE 18 Gy 2 3) Oo ‘Typically, the total number of values inside the IN clause is variable, Therefore, we need to create a placeholder that can support a dynamic list of values. 2.1. With JdbcTemplate \With JabcTemplate thttps//docs springio/spring framework /does/current/javadoc~ api/org/springtramework/jdbe/core/JdbcTemplate html. we can use characters as placeholders for the lst of values, The number of characters will be the same as the size of the list IBM FlashSystem - Le stockage qui fait v la différence wv mM 1M Learn (https /ads reestarcom/? Listamployee> gett loyneFranfcliat(istcinteger> 18) ( Oo Sting iat = seengsointh Soest onesnptetiee i200, Listeteployee> exployees = jdbeTemplate-query( String. format ("SELECT * FROM EMPLOYEE WHERE 1d ZN (Hs)", JnSaQ), ds. toarray() (+5, rowum) > new EMployee(rs.gotine ("id"), rs.getstring "First none"), rs.getString(*tast_ome")))5 return enployees: In this method, we first generate a placeholder string that contains ids size" characters separated with commas \Vjava-strings-concatenation). Then we put this string into the IN clause of our SQL statement. For example. if we have throe numbers in the ids st. the SQL statornent is: SELECT + FROM ENPLOVEE WHERE 46 IN (2,2,7) ia Inthe query method, we pass the idslist as a parameter to match the placeholders inside the IN clause. This way, ‘we can execute a dynamic SQL statement based on the input list of values. 2.2. With NamedParameterJdbcTemplate Another way to handle the dynamic list of values is to use NamedParameteridibcTemplate {httpsi//does.spring.o/spring/does /current/javadoc- api/org/springframework/jdbc/core/namedparam/NamedParameteridoctemplate html. For example, we can irectly create a named parameter for the input ist: hiipsulwaewcbaeidung,comlspring-jdbctemplate-insit 26 03112023 2031 Using a List of Values ina JabeTemplate IN Clause | Bacldung Listeempl sse- society aseFrddicListhaned(Listeinteger> sds) ( oO ‘SclParenetersource parameters = new MapSqlParanetersourca( "ids", ics); Listeceplayee> eaployecs + nanedidbeTenplate.query( "SELECT » FROW EMPLOYEE WHERE 4d IN (:1ds)", (75, rowum) > new EMDLoyee(rs.gotine ("id"), rs.getstring "First nore regetString(*last_same")))3 return enployees: In this method, we first construct a MapSqlParameterSource thitps://docs springlo/spring/docs/eurrent/javadoc- api/org/springframework/jdbe/core/namedparam/MapSqlParameterSource htm) object that contains the input id list. Then we only use one named parameter to represent the dynamic list of values. Under the hood, NamedParameteniaycTemplate substitutes the named parameters for the placeholders, and. Uses JabcTemplate to execute the query. IBM FlashSystem - Le stockage qui fait v la différence wy 2M BM Lea : (https /ads reestarcom/? 3. Handling a Large List When we have a large number of values in alist, we should consider alternate ways to pass them into the JdbcTemplate query. For example, the Oracle database doesnt support more than 1.000 literals in an IN clause. ‘One way to do ths is to create a temporary table for the list. However, different databases can have different ‘ways to create temporary tables. For instance, we can use the CREATE GLOBAL TEMPORARY TABLE (https://docs oracle. com /edi/B28359_01/server111/b28310 /tables003.htm#ADMINI1633) statomont to croate a temporary table in the Oracle database. Lets create a temporary table for the H database: Listcemployee> getEmployeasFromLargeldList(Listeinteger> sds) ( jdocTenplave-execuce "CREATE TEMPORARY TABLE IF NOT EXISTS emptoyee.tnp (4¢ INT NOT HULL") Listeauject(]> enployeetds = new ArrayList©>()s for (integer id: ids) { enployeetds.adé(new Object] ¢ id )s } jdocTenpLave.batchupdate(“INSERT INTO employee. tmp VALUES(?)", enploysers): us cenployee> enployees = jdbcTenplate.query( ELECT + FROM EMPLOYEE WHERE id IN (SELECT 1@ FROM enptoyee.enp)", (75, rowMum) > new EMDloyee(rs.gotIne ("id"), rsigetstring "First nace") rs.getString("last_same"))); $jdocTenplave-update("ELETE FROM employee. cmp"); return employees; Hore. we frst create a temporary table to hold all the values ofthe input ist. Then we insert the input list's values into the table. v hiipsulwaewcbaeidung,comlspring-jdbctemplate-insit a6 03112023 20:31 Using a List of Values ina JabeTemplate IN Clause | Baeldung “ Inour resulting SQL statement, the values in the IN clause are from the temporary table, and we avoid constructing an IN clause with a large number of placeholders. Finally. after we finish the query. we can clean up the temporary table for futuro use. 4. Conclusion Inthis article, we demonstrated how to use JalbcTemplate and NamedParameteriabcTemplate to pass a list of values for the IN clause of a SQL query, We also provided an alternate way to handle a large number of list values by using a temporary table. As always, the source code for the article is available over on GitHub {hitps://githuiscom/eugenp/tutorials/tree/master/persistence-modules/spring jdbc). Get started with Spring Data JPA through the reference Learn Spring Data JPA course: >> CHECK OUT THE COURSE (/leam-spring-data-jpa-course#table) ‘An intro to Spring Data, JPA and Transaction Semantics Details with JPA Get Persistence Right with Spring Download the E-book (/persistence-with-spring) ‘Comments are closed on this article! y htipsifwnww.bacldung,comlspring-jabctomplate-insist 46 03112023 20:31 “ ‘COURSES SERIES ‘ABOUT htipsifwnww.bacldung,comlspring-jabctomplate-insist Using a List of Values ina JabeTemplate IN Clause | Baeldung 56

You might also like