라이브러리 추가
build.gradle
implementation 'org.springframework.boot:spring-boot-starter-jdbc'
runtimeOnly 'com.h2database:h2'
Spring Boot database 연결 설정 추가
application.properties
spring.datasource.url=jdbc:h2:tcp://localhost/~/test
spring.datasource.driver-class-name=org.h2.Driver
spring.datasource.username=sa
JDBC API 로 구현하는것은 너무 오래전 이야기이기 때문에 참고만 하자
package hello.hellospring.repository;
import hello.hellospring.domain.Member;
import org.springframework.jdbc.datasource.DataSourceUtils;
import javax.sql.DataSource;
import java.sql.*;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
public class JdbcMemberRepository implements MemberRepository {
private final DataSource dataSource;
public JdbcMemberRepository(DataSource dataSource) {
this.dataSource = dataSource;
}
@Override
public Member save(Member member) {
// 상수로 빼는 것이 더 좋음
String sql = "insert into member(name) values(?)";
Connection conn = null;
PreparedStatement pstmt = null;
// 결과 값
ResultSet rs = null;
try {
// 1. connection 가져오기
conn = getConnection();
// 2. prepareStatement를 통해서 sql 넣고,
// 3. RETURN_GENARATED_KEYS : db에 insert 하여 id 값 생성
pstmt = conn.prepareStatement(sql,
Statement.RETURN_GENERATED_KEYS);
// 4. 첫번째 '?' 변수에 값 넣음
pstmt.setString(1, member.getName());
// 5. 실제 db쿼리에 업데이트 됨
// executeUpdate : 생성할 때
pstmt.executeUpdate();
// 6. 결과로 generateKey를 반환 해줌 (PK값)
rs = pstmt.getGeneratedKeys();
// 만약에 result 값이 있다면
if (rs.next()) {
// 값을 가져옴
member.setId(rs.getLong(1));
} else {
throw new SQLException("id 조회 실패");
}
return member;
} catch (Exception e) {
throw new IllegalStateException(e);
} finally {
// 사용 후에는 무조건 close를 해줘야 함
close(conn, pstmt, rs);
}
}
@Override
public Optional<Member> findById(Long id) {
// 쿼리 생성
String sql = "select * from member where id = ?";
Connection conn = null;
PreparedStatement pstmt = null;
ResultSet rs = null;
try {
conn = getConnection();
pstmt = conn.prepareStatement(sql);
pstmt.setLong(1, id);
// executeQuery() : 조회할 때
rs = pstmt.executeQuery();
if(rs.next()) {
// 값이 있으면 member 객체 생성하고 반환
Member member = new Member();
member.setId(rs.getLong("id"));
member.setName(rs.getString("name"));
return Optional.of(member);
} else {
// 없을 경우 empty return
return Optional.empty();
}
} catch (Exception e) {
throw new IllegalStateException(e);
} finally {
close(conn, pstmt, rs);
}
}
@Override
public Optional<Member> findByName(String name) {
String sql = "select * from member where name = ?";
Connection conn = null;
PreparedStatement pstmt = null;
ResultSet rs = null;
try {
conn = getConnection();
pstmt = conn.prepareStatement(sql);
pstmt.setString(1, name);
rs = pstmt.executeQuery();
if (rs.next()) {
Member member = new Member();
member.setId(rs.getLong("id"));
member.setName(rs.getString("name"));
return Optional.of(member);
}
return Optional.empty();
} catch (Exception e) {
throw new IllegalStateException(e);
} finally {
close(conn, pstmt, rs);
}
}
@Override
public List<Member> findAll() {
String sql = "select * from member";
Connection conn = null;
PreparedStatement pstmt = null;
ResultSet rs = null;
try {
conn = getConnection();
pstmt = conn.prepareStatement(sql);
rs = pstmt.executeQuery();
List<Member> members = new ArrayList<>();
while (rs.next()) {
Member member = new Member();
member.setId(rs.getLong("id"));
member.setName(rs.getString("name"));
members.add(member);
}
return members;
} catch (Exception e) {
throw new IllegalStateException(e);
} finally {
close(conn, pstmt, rs);
}
}
private Connection getConnection() {
return DataSourceUtils.getConnection(dataSource);
}
private void close(Connection conn, PreparedStatement pstmt, ResultSet rs) {
// 생성된 역순으로 close 해줘야 함
try {
if (rs != null) {
rs.close();
}
} catch (SQLException e) {
e.printStackTrace();
}
try {
if (pstmt != null) {
pstmt.close();
}
} catch (SQLException e) {
e.printStackTrace();
}
try {
if (conn != null) {
close(conn);
}
} catch (SQLException e) {
e.printStackTrace();
}
try {
if (conn != null) {
close(conn);
}
} catch (SQLException e) {
e.printStackTrace();
}
}
private void close(Connection conn) throws SQLException {
DataSourceUtils.releaseConnection(conn, dataSource);
}
}
spring framework 사용하여 데이터베이스에 접근하고 close할 때에는
DataSourceUtils
를 통해 접근해야 함
SpringConfig
package hello.hellospring;
import hello.hellospring.repository.JdbcMemberRepository;
import hello.hellospring.repository.MemberRepository;
import hello.hellospring.repository.MemoryMemberRepository;
import hello.hellospring.service.MemberService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import javax.sql.DataSource;
@Configuration
public class SpringConfig {
private DataSource dataSource;
@Autowired
public SpringConfig(DataSource dataSource){
this.dataSource = dataSource;
}
@Bean
public MemberService memberService(){
return new MemberService(memberRepository());
}
@Bean
public MemberRepository memberRepository(){
return new JdbcMemberRepository();
}
}
JdbcRepository 와 SpringConfig만 수정해서 데이터베이스 접근 수정
DataSource는 데이터베이스 Connection 을 획득할 때 사용하는 객체, SpringBoot 는 database connection 정보를 바탕으로 datasource를 생성하고 spring bean으로 만들어두기 때문에 DI를 받을 수 있음
→ 서비스 코드 수정 없이 Application 설정 코드만 수정하면 데이터 접근 방법을 쉽게 수정할 수 있음
개방-폐쇄 원칙 (OCP)
: 확장에는 열려있고, 수정&변경에는 닫혀있음
스프링의 DI(Dependencies Injection)를 사용하면 기존코드를 전혀 손대지 않고, 설정만으로 구현 클래스를 변경할 수 있다.