이번글은 공식 문서에서 소개하는 Using the JDBC Core Classes to Control Basic JDBC Processing and Error Handling에 대해 정리했습니다.
Running Statements
Running an SQL statement requires very little code. You need a DataSource and a JdbcTemplate, including the convenience methods that are provided with the JdbcTemplate. The following example shows what you need to include for a minimal but fully functional class that creates a new table:
SQL 문을 실행하는 데에는 코드가 거의 필요하지 않습니다.
DataSource와 JdbcTemplate이 필요하며, JdbcTemplate이 제공하는 편의 메서드도 함께 사용할 수 있습니다.
아래 예제는 새로운 테이블을 생성하기 위한 최소한의 구성으로, 완전히 동작 가능한 클래스를 작성할 때 포함해야 할 내용을 보여줍니다.
public class ExecuteAStatement {
private JdbcTemplate jdbcTemplate;
public void setDataSource(DataSource dataSource) {
this.jdbcTemplate = new JdbcTemplate(dataSource);
}
public void doExecute() {
this.jdbcTemplate.execute("create table mytable (id integer, name varchar(100))");
}
}
Running Queries
Some query methods return a single value. To retrieve a count or a specific value from one row, use queryForObject(..). The latter converts the returned JDBC Type to the Java class that is passed in as an argument. If the type conversion is invalid, an InvalidDataAccessApiUsageException is thrown. The following example contains two query methods, one for an int and one that queries for a String
일부 쿼리 메서드는 하나의 값만 반환합니다. 행 수나 특정 값을 한 행에서 조회하려면 queryForObject(..)를 사용합니다. 이 메서드는 반환된 JDBC 타입을 인자로 전달된 Java 클래스 타입으로 변환합니다. 만약 타입 변환이 유효하지 않으면InvalidDataAccessApiUsageException이 발생합니다. 다음 예제는 하나는 int 값을, 다른 하나는 String 값을 조회하는 두 개의 쿼리 메서드를 포함하고 있습니다.
public class RunAQuery {
private JdbcTemplate jdbcTemplate;
public void setDataSource(DataSource dataSource) {
this.jdbcTemplate = new JdbcTemplate(dataSource);
}
public int getCount() {
return this.jdbcTemplate.queryForObject("select count(*) from mytable", Integer.class);
}
public String getName() {
return this.jdbcTemplate.queryForObject("select name from mytable", String.class);
}
}
In addition to the single result query methods, several methods return a list with an entry for each row that the query returned. The most generic method is queryForList(..), which returns a List where each element is a Map containing one entry for each column, using the column name as the key. If you add a method to the preceding example to retrieve a list of all the rows, it might be as follows:
단일 결과를 반환하는 쿼리 메서드 외에도, 쿼리가 반환한 각 행마다 하나의 항목이 포함된 리스트를 반환하는 여러 메서드들이 있습니다.
가장 일반적인 메서드는 queryForList(..)이며, 이 메서드는 각 요소가 맵(Map)인 리스트를 반환한다. 이 맵은 각 열에 대해 하나의 항목을 가지며, 열 이름을 키로 사용합니다. 앞선 예제에 모든 행의 리스트를 조회하는 메서드를 추가한다면, 다음과 같을 수 있습니다.
private JdbcTemplate jdbcTemplate;
public void setDataSource(DataSource dataSource) {
this.jdbcTemplate = new JdbcTemplate(dataSource);
}
public List<Map<String, Object>> getList() {
return this.jdbcTemplate.queryForList("select * from mytable");
}
In the preceding example, an SQL statement has placeholders for row parameters. You can pass the parameter values in as varargs or, alternatively, as an array of objects. Thus, you should explicitly wrap primitives in the primitive wrapper classes, or you should use auto-boxing.
앞선 예제에서, SQL 문은 행의 파라미터들을 위한 플레이스홀더를 가지고 있습니다.
파라미터 값들은 varags(가변 인자)로 전달할 수도 있고, 또는 객체 배열로 전달할 수도 있습니다. 따라서, 원시 타입을 사용할 경우, 명시적으로 해당 값을 프리미티브 래퍼 클래스(예:Integer, Long)로 감싸주거나, 자동 박싱(auto-boxing)을 사용해야 합니다.
Retrieving Auto-generated Keys
An update() convenience method supports the retrieval of primary keys generated by the database. This support is part of the JDBC 3.0 standard. See Chapter 13.6 of the specification for details. The method takes a PreparedStatementCreator as its first argument, and this is the way the required insert statement is specified. The other argument is a KeyHolder, which contains the generated key on successful return from the update. There is no standard single way to create an appropriate PreparedStatement (which explains why the method signature is the way it is). The following example works on Oracle but may not work on other platforms:
update() 편의 메서드는 데이터베이스에서 생성된 기본 키(primary key)를 조회하는 기능을 지원합니다. 이 기능은 JDBC 3.0 표준의 일부입니다. 자세한 내용은 명세의 13.6장을 참고하세요.
이 메서드는 첫 번째 인자로 PreparedStatementCreator를 받는데, 이 인자를 통해 필요한 insert 문을 지정합니다.
다른 인자는 KeyHolder이며, 이는 update() 메서드가 성공적으로 실행된 후 생성된 키를 담고 있습니다.
적절한 PreparedStatement를 생성하는 데 있어 하나의 표준적인 방법은 존재하지 않으며, 이 점이 해당 메서드의 시그니처가 그렇게 되어 있는 이유를 설명해줍니다. 다음 예제는 오라클에서는 동작하지만, 다른 플랫폼에서는 동작하지 않을 수 있다.
final String INSERT_SQL = "insert into my_test (name) values(?)";
final String name = "Rob";
KeyHolder keyHolder = new GeneratedKeyHolder();
jdbcTemplate.update(connection -> {
PreparedStatement ps = connection.prepareStatement(INSERT_SQL, new String[] { "id" });
ps.setString(1, name);
return ps;
}, keyHolder);
// keyHolder.getKey() now contains the generated key
KeyHolder는 DB에서 자동 생성된 기본 키를 담기 위한 객체입니다.
JdbcTemplate.update(...) 메서드 실행이 성공하게 되면, DB가 생성한 key 값이 KeyHolder에 저장됩니다.
'공식문서' 카테고리의 다른 글
[Spring Docs] Controlling Database Connection (0) | 2025.04.02 |
---|---|
Garbage Collector #4 (0) | 2025.04.01 |
[Spring Docs] Using the JDBC Core Classes to Control Basic JDBC Processing and Error Handling #2 (0) | 2025.03.30 |
[Spring Docs] Using the JDBC Core Classes to Control Basic JDBC Processing and Error Handling #1 (0) | 2025.03.28 |
[Spring Docs] Package Hierarchy (0) | 2025.03.27 |