Notice
Recent Posts
Recent Comments
Link
일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
1 | ||||||
2 | 3 | 4 | 5 | 6 | 7 | 8 |
9 | 10 | 11 | 12 | 13 | 14 | 15 |
16 | 17 | 18 | 19 | 20 | 21 | 22 |
23 | 24 | 25 | 26 | 27 | 28 |
Tags
- 멋사12
- 멋사 10기
- 파이썬 크롤링
- 멋사 합격
- 멋사 서류평가
- 멋쟁이 사자처럼
- 깃허브
- django
- 멋쟁이사자처럼대학
- 기사 제목 크롤링
- discord
- IT동아리
- 백엔드
- 멋쟁이사자처럼 서류
- 코딩동아리
- 멋사 면접
- 멋사 서류
- 멋사
- 멋쟁이사자처럼
- 멋사11기
- 크롤링
- 알림봇
- 웹동아리
- 멋쟁이사자처럼10기
- 멋사10기
- 파이썬
- API
- 디스코드봇
- ㅏㄴ
- 멋쟁이사자처럼11기
Archives
- Today
- Total
ACHO.pk devlog
[Springboot] 순수 JDBC 본문
인프런 김영한 강사님의 "스프링 입문 - 코드로 배우는 스프링 부트, 웹 MVC, DB 접근 기술"의 강의를 듣고 학습하였습니다.
1. JDBC
자바와 DB(H2)를 이어주는 드라이버, 과거에 쓰던 방법이다.
1-1. 스프링 설정 변경
build.gradle 파일에 jdbc, h2 데이터베이스 관련 라이브러리 추가 및 수정을 한다.
implementation 'org.springframework.boot:spring-boot-starter-jdbc'
runtimeOnly 'com.h2database:h2'
1-2. 스프링 부트 데이터베이스 연결 설정 추가
▹resources/application.properties
형광펜 칠한 url를 아래 코드에서 "본인"에 넣어주면 된다
spring.datasource.url=본인
spring.datasource.driver-class-name=org.h2.Driver
spring.datasource.username=sa
주의
스프링부트 2.4부터는 spring.datasource.username=sa 를 꼭 추가해주어야 한다. 그렇지 않으면 Wrong user name or password 오류가 발생한다. 참고로 다음과 같이 마지막에 공백이 들어가면 같은 오류가 발생한다. spring.datasource.username=sa 공백 주의, 공백은 모두 제거해야 한다.
1-3. Jdbc 회원 레포지토리 구현
package Springboot.study.repository;
import Springboot.study.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 {
conn = getConnection();
pstmt = conn.prepareStatement(sql,
Statement.RETURN_GENERATED_KEYS);
pstmt.setString(1, member.getName());
pstmt.executeUpdate();
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);
}
}
'프레임워크 > Springboot' 카테고리의 다른 글
[Springboot] 스프링 JdbcTemplate (0) | 2023.01.25 |
---|---|
[Springboot] 스프링 통합 테스트 (0) | 2023.01.24 |
[Springboot] H2 데이터베이스 설치 (0) | 2023.01.22 |
[Springboot] 회원 웹 기능(홈 화면 추가, 등록, 조회) (0) | 2023.01.22 |
[Springboot] 자바 코드로 직접 스프링 빈 등록하기 (0) | 2023.01.21 |
Comments