Merge pull request #9100 from wugangca/BAEL-3961

BAEL-3961 Using a list of values in a JDBCTemplate IN clause
This commit is contained in:
Eric Martin 2020-04-23 20:08:02 -05:00 committed by GitHub
commit 5738683a5b
5 changed files with 120 additions and 21 deletions

View File

@ -7,7 +7,12 @@ public class Employee {
private String lastName;
private String address;
public Employee(int id, String firstName, String lastName) {
this.id = id;
this.firstName = firstName;
this.lastName = lastName;
}
public int getId() {
return id;
@ -33,12 +38,5 @@ public class Employee {
this.lastName = lastName;
}
public String getAddress() {
return address;
}
public void setAddress(final String address) {
this.address = address;
}
}

View File

@ -1,21 +1,67 @@
package com.baeldung.jdbc;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import javax.sql.DataSource;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.namedparam.MapSqlParameterSource;
import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate;
import org.springframework.jdbc.core.namedparam.SqlParameterSource;
import org.springframework.stereotype.Repository;
@Repository
public class EmployeeDAO {
private JdbcTemplate jdbcTemplate;
private NamedParameterJdbcTemplate namedJdbcTemplate;
public void setDataSource(DataSource dataSource) {
jdbcTemplate = new JdbcTemplate(dataSource);
namedJdbcTemplate = new NamedParameterJdbcTemplate(dataSource);
}
public int getCountOfEmployees() {
return jdbcTemplate.queryForObject("SELECT COUNT(*) FROM EMPLOYEE", Integer.class);
}
public List<Employee> getEmployeesFromIdListNamed(List<Integer> ids) {
SqlParameterSource parameters = new MapSqlParameterSource("ids", ids);
List<Employee> employees = namedJdbcTemplate.query(
"SELECT * FROM EMPLOYEE WHERE id IN (:ids)",
parameters,
(rs, rowNum) -> new Employee(rs.getInt("id"), rs.getString("first_name"), rs.getString("last_name")));
return employees;
}
public List<Employee> getEmployeesFromIdList(List<Integer> ids) {
String inSql = String.join(",", Collections.nCopies(ids.size(), "?"));
List<Employee> employees = jdbcTemplate.query(
String.format("SELECT * FROM EMPLOYEE WHERE id IN (%s)", inSql),
ids.toArray(),
(rs, rowNum) -> new Employee(rs.getInt("id"), rs.getString("first_name"), rs.getString("last_name")));
return employees;
}
public List<Employee> getEmployeesFromLargeIdList(List<Integer> ids) {
jdbcTemplate.execute("CREATE TEMPORARY TABLE IF NOT EXISTS employee_tmp (id INT NOT NULL)");
List<Object[]> employeeIds = new ArrayList<>();
for (Integer id : ids) {
employeeIds.add(new Object[] { id });
}
jdbcTemplate.batchUpdate("INSERT INTO employee_tmp VALUES(?)", employeeIds);
List<Employee> employees = jdbcTemplate.query(
"SELECT * FROM EMPLOYEE WHERE id IN (SELECT id FROM employee_tmp)",
(rs, rowNum) -> new Employee(rs.getInt("id"), rs.getString("first_name"), rs.getString("last_name")));
jdbcTemplate.update("DELETE FROM employee_tmp");
return employees;
}
}

View File

@ -2,6 +2,5 @@ CREATE TABLE EMPLOYEE
(
ID int NOT NULL PRIMARY KEY,
FIRST_NAME varchar(255),
LAST_NAME varchar(255),
ADDRESS varchar(255)
LAST_NAME varchar(255)
);

View File

@ -1,4 +1,4 @@
INSERT INTO EMPLOYEE VALUES (1, 'James', 'Gosling', 'Canada');
INSERT INTO EMPLOYEE VALUES (2, 'Donald', 'Knuth', 'USA');
INSERT INTO EMPLOYEE VALUES (3, 'Linus', 'Torvalds', 'Finland');
INSERT INTO EMPLOYEE VALUES (4, 'Dennis', 'Ritchie', 'USA');
INSERT INTO EMPLOYEE VALUES (1, 'James', 'Gosling');
INSERT INTO EMPLOYEE VALUES (2, 'Donald', 'Knuth');
INSERT INTO EMPLOYEE VALUES (3, 'Linus', 'Torvalds');
INSERT INTO EMPLOYEE VALUES (4, 'Dennis', 'Ritchie');

View File

@ -2,8 +2,12 @@ package com.baeldung.jdbc;
import static org.junit.jupiter.api.Assertions.assertEquals;
import java.util.ArrayList;
import java.util.List;
import javax.sql.DataSource;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
@ -14,13 +18,24 @@ import org.springframework.jdbc.datasource.embedded.EmbeddedDatabaseBuilder;
import org.springframework.jdbc.datasource.embedded.EmbeddedDatabaseType;
import org.springframework.test.util.ReflectionTestUtils;
@RunWith(MockitoJUnitRunner.class)
public class EmployeeDAOUnitTest {
@Mock
JdbcTemplate jdbcTemplate;
DataSource dataSource;
@Before
public void setup() {
dataSource = new EmbeddedDatabaseBuilder().setType(EmbeddedDatabaseType.H2)
.generateUniqueName(true)
.addScript("classpath:jdbc/schema.sql")
.addScript("classpath:jdbc/test-data.sql")
.build();
}
@Test
public void whenMockJdbcTemplate_thenReturnCorrectEmployeeCount() {
EmployeeDAO employeeDAO = new EmployeeDAO();
@ -38,14 +53,55 @@ public class EmployeeDAOUnitTest {
@Test
public void whenInjectInMemoryDataSource_thenReturnCorrectEmployeeCount() {
DataSource dataSource = new EmbeddedDatabaseBuilder().setType(EmbeddedDatabaseType.H2)
.addScript("classpath:jdbc/schema.sql")
.addScript("classpath:jdbc/test-data.sql")
.build();
EmployeeDAO employeeDAO = new EmployeeDAO();
employeeDAO.setDataSource(dataSource);
assertEquals(4, employeeDAO.getCountOfEmployees());
}
@Test
public void givenSmallIdList_whenGetEmployeesFromIdList_thenReturnCorrectEmployees() {
List<Integer> ids = new ArrayList<>();
ids.add(1);
ids.add(3);
ids.add(4);
EmployeeDAO employeeDAO = new EmployeeDAO();
employeeDAO.setDataSource(dataSource);
List<Employee> employees = employeeDAO.getEmployeesFromIdList(ids);
assertEquals(3, employees.size());
assertEquals(1, employees.get(0).getId());
assertEquals(3, employees.get(1).getId());
assertEquals(4, employees.get(2).getId());
employees = employeeDAO.getEmployeesFromIdListNamed(ids);
assertEquals(3, employees.size());
assertEquals(1, employees.get(0).getId());
assertEquals(3, employees.get(1).getId());
assertEquals(4, employees.get(2).getId());
}
@Test
public void givenLargeIdList_whenGetEmployeesFromIdList_thenReturnCorrectEmployees() {
List<Integer> ids = new ArrayList<>();
ids.add(1);
ids.add(3);
ids.add(4);
EmployeeDAO employeeDAO = new EmployeeDAO();
employeeDAO.setDataSource(dataSource);
List<Employee> employees = employeeDAO.getEmployeesFromLargeIdList(ids);
assertEquals(3, employees.size());
assertEquals(1, employees.get(0).getId());
assertEquals(3, employees.get(1).getId());
assertEquals(4, employees.get(2).getId());
ids.clear();
ids.add(2);
employees = employeeDAO.getEmployeesFromLargeIdList(ids);
assertEquals(1, employees.size());
}
}