Framekwork/SPRING
[자바/스프링] 순수 JDBC
아이엠제니
2023. 2. 24. 07:30
스프링 DB 접근 기술
순수 JDBC
🔎 환경 설정
👉 build.gradle 파일에 jdbc, h2 데이터베이스 관련 라이브러리 추가
```
implementaion 'org.springframework.boot:spring-boot-starter-jdbc'
runtimeOnly 'com.h2database:h2'
```
💾 build.gradle
👉 스프링 부트 데이터베이스 연결 설정 추가
`resources/application.properties`
```
spring.datasource.url=jdbc:h2:tcp://localhost/~/test
spring.datasource.driver-class-name=org.h2.Driver
```
💾 resources > application.properties
에러 뜨면 오른쪽 위에 코끼리(?) 모양 버튼 눌러서 import 해준다.
띠용.
에러 뜸.
강의에서는 굳이 username이나 password를 안 써도 된다고 했는데...!
넣지 않으니 에러가 떴다.
그래서 username 추가함.
spring.datasource.username=sa
실행해보니 에러 안 뜸.
(강의 자료를 보니 스프링 부트 2.4부터는 username을 꼭 추가해야 한다고 한다.)
🔎 Jdbc 리포지토리 구현
❗ 주의! 이렇게 JDBC API로 직접 코딩하는 것은 15년 전 이야기이다. 따라서 고대 개발자들이 이렇게 고생하고 살았구나 생각하고, 정신건강을 위해 참고만 하고 넘기자
- 자바랑 db랑 연동하려면 JDBC 드라이가 꼭 있어야 한다.
이걸 가지고 서로 연동을 함 - db랑 연동할 때 클라이언트가 필요한데, 그 역할 h2가 함
💾 repository > JdbcMemberRepository.java
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 {
// db에 붙으려면 datasource 라는 게 필요함
// spring을 통해 데이터소스를 주입받아야 함
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 {
conn = getConnection(); // connection을 가져옴
/*
* statement: SQL 구문을 실행하는 역할
* RETURN_GENERATED_KEYS: null 값일 때 자동으로 id 값을 얻을 수 있었던 거, h2에서도 설정했었음
* */
pstmt = conn.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS);
pstmt.setString(1, member.getName());
pstmt.executeUpdate(); // executeUpdate(): db에 실제로 전달됨
rs = pstmt.getGeneratedKeys(); // 키를 자동으로 꺼내줌
if (rs.next()) { // 값이 있으면 값을 꺼내면 됨
member.setId(rs.getLong(1));
} else {
throw new SQLException("id 조회 실패");
}
return member;
} catch (Exception e) {
throw new IllegalStateException(e);
} finally {
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);
rs = pstmt.executeQuery(); // 조회
if (rs.next()) { // 값이 있으면 멤버 객체를 만든다
Member member = new Member();
member.setId(rs.getLong("id"));
member.setName(rs.getString("name"));
return Optional.of(member);
} else {
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);
}
}
@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);
}
}
private Connection getConnection() {
return DataSourceUtils.getConnection(dataSource);
}
private void close(Connection conn, PreparedStatement pstmt, ResultSet rs) {
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();
}
}
private void close(Connection conn) throws SQLException {
DataSourceUtils.releaseConnection(conn, dataSource);
}
}
💾 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 읽고,
* @Bean을 스프링 빈에 등록하는 거라고 인식함
* */
@Configuration
public class SpringConfig {
private final DataSource dataSource;
@Autowired
public SpringConfig(DataSource dataSource) {
this.dataSource = dataSource;
}
@Bean // 스프링 빈을 등록할 거임
public MemberService memberService() {
return new MemberService(memberRepository());
}
@Bean
public MemberRepository memberRepository() {
// return new MemoryMemberRepository();
return new JdbcMemberRepository(dataSource);
}
}
dataSource 밑줄 오류...
인텔리제이 자체 오류라고 한다.
돌려보니 에러는 안 나서 그대로 진행.
DataSource는 데이터베이스 커넥션을 획득할 때 사용하는 객체다. 스프링 부트는 데이터베이스 커넥션 정보를 바탕으로 DataSource를 생성하고 스프링 빈으로 만들어둔다. 그래서 DI를 받을 수 있다.
localhost:8080 가서 확인을 해보자.
db에서 등록했던 내용 확인 가능! (감동...)
새로고침하면 사라지던 그때의 홈페이지가 아니다.
추가로 `jpa`를 등록했다.
3번에 jpa도 들어왔다! (역시나 감동...)
h2 db에서도 확인해봤더니!
내가 입력한 `jpa`가 잘 들어온 걸 확인할 수 있었다. (굿)
- 개방-폐쇄 원칙(OCP, Open-Closed Principle)
- 확장에는 열려있고, 수정, 변경에는 닫혀있다.
- 스프링의 DI(Dependencies Injjection)을 사용하면 기존 코드를 전혀 손대지 않고, 설정만으로 구현 클래스를 변경할 수 있다.
- 회원을 등록하고 DB에 결과가 잘 입력되는지 확인하자.
- 데이터를 DB에 저장하므로 스프릥 서버를 다시 실행해도 데이터가 안전하게 저장된다.
다형성
프로그램 언어의 다형성은 그 프로그래밍 언어의 자료형 체계의 성질을 나타내는 것으로, 프로그램 언어의 각 요소들이 다양한 자료형에 속하는 것이 허가되는 성질을 카리킨다. 반댓말은 단형성으로, 프로그램 언어의 각 요소가 한가지 형태만 가지는 성질을 가리킨다.
[스프링 입문 - 코드로 배우는 스프링 부트, 웹 MVC, DB 접근 기술] 강의 기록
300x250