정의: 자바에서 데이터베이스에 접속이 가능하도록 하는 API
JDBC 주요 구성
DBMS와 통신을 담당하는 자바 클래스
DBMS에 따라 맞는 드라이버가 다름
ex: com.mysql.jdbc.Driver(mySQL), oracle.jdbc.driver.OracleDriver(오라클)
JdbcTemplate
스프링에서 JDBC 지원을 위한 클래스
JDBC 사용 시 요구되는 형식적인 코드없이 SQL 연산을 수행하도록 제공
JdbcTemplate 사용 여부에 따른 비교
@Override
public Ingredient findById(String id) {
Connection connection = null; // DB 연결을 위한 객체
PreparedStatement statement = null; // 쿼리문 정의를 위한 객체
Resultset resultSet = null; // 결과값 저장을 위한 객체
try {
connection = dataSource.getConnection(); // DB 연결
statement = connection.preparedStatement(
"select id, name, type from Ingredient where id = ?");
statement.setString(1, id);
resultSet = statement.executeQuery(); // 쿼리 수행 및 결과 저장
Ingredient ingredient = null; // 쿼리 결과를 객체에 매핑시키기 위함
if (resultSet.next()) {
ingredient = new Ingredient(
resultSet.getString("id"),
resultSet.getString("name"),
Ingredient.Type.valueOf(resultSet.getString("type")));
}
return ingredient;
} catch (SQLException e) {
// SQL 수행에 관한 예외 처리
} finally {
// 쿼리 수행 후 관련 객체 해제
if (resultSet != null) {
try {
resultSet.close();
} catch (SQLException e) {}
}
if (statement != null) {
try {
statement.close();
} catch (SQLException e) {}
}
if (connection != null) {
try {
connection.close();
} catch (SQLException e) {}
}
}
return null;
}
private JdbcTemplate jdbc; // JdbcTemplate 활용 쿼리 수행을 위한 객체
@Override
public Ingredient findById(String id) {
return jdbc.queryForObject(
"select id, name, type from Ingredient where id = ?",
this::mapRowToIngredient, id);
}
private Ingredient mapRowToIngredient(ResultSet rs, int rowNum) throws SQLException {
return new Ingredient(
rs.getString("id");
rs.getString("name");
Ingredient.Type.valueOf(rs.getString("type")));
}
비교 결과
주요 메소드 및 어노테이션
데이터 추가를 위한 방법
1) 직접 update 메소드를 사용
Create(생성), Read(읽기), Update(변경), Delete(삭제) 연산을 위한 인터페이스
매개변수로 저장되는 엔티티 타입과 ID 속성타입을 받음
ex) CrudRepository<Ingredient, Long>: 엔티티타입은 Ingredient, ID 속성타입은 Long