backend
  • README
  • DOCS
    • Java Docs
    • Servlet Docs
    • JSP Docs
    • DB & SQL Docs
    • Spring Boot Docs
    • Spring Security Docs
    • AWS Docs
  • 설치하기
    • Intellij 설정
  • 자바
    • 01 Java란?
    • 02 자바 시작하기
    • 03 자료형과 연산자
    • 04 제어문
    • 05 메소드
    • 06 클래스 기초
      • Static 보충자료
      • 패키지 보충자료
    • 07 객체지향 프로그래밍
    • 08 클래스 더 알아보기
      • 열거형 ENUM 보충자료
    • 09 클래스와 자료형
      • 다형성 보충자료
      • 제네릭 보충자료
    • 10 컬렉션 프레임워크
      • 컬렉션 프레임워크 보충자료
    • 11 람다식과 함수형 프로그래밍
      • 람다식 보충자료
    • 12 오류 대비하기
      • 오류 보충자료
    • 13 멀티태스킹
      • 멀티태스킹 보충자료
    • 교재보충
      • java.lang
  • 스프링
    • 서블릿, JSP
      • 05 Servlet(서블릿)
        • 서블릿 보충자료
        • 서블릿 추가코드
        • XML, YAML, JSON
      • 06 JSP(자바 서버 페이지)
        • JSP 보충자료
      • 07 JSTL(JSP 스탠다드 태그 라이브러리)
        • JSTL 보충자료
      • 08 Cookie(쿠키), Session(세션)
      • 09 서블릿,필터,리스너
        • 서블릿,필터,리스너 보충자료
      • 11 도서관리 프로젝트 실습
    • Spring Boot
      • 01 스프링 등장 배경, 객체지향
        • 스프링 등장 배경, 객체지향 보충자료
      • 02 IOC(제어의 역전), DI(의존성 주입)
        • IOC 보충자료
        • DI 보충자료
      • 03 스프링 구조
        • 스프링 구조 보충설명
      • 04 테스트코드 실습
      • 05 스프링 빈 설정
        • 스프링 빈 설정 보충자료
      • 06 싱글톤
        • 싱글톤 보충 자료
      • 07 스프링 빈 자동설정
        • 스프링 빈 자동설정 보충자료
      • 08 빈 생명주기
        • 빈 생명주기 보충자료
      • 09 빈 스코프
        • 빈 스코프 보충자료
      • 10 스프링 MVC
        • 스프링 MVC 보충자료
        • 데이터베이스 연동에 필요한 부분
      • 11 Validation(검증)
        • Validation(검증) 보충자료
      • 12 Bean Validation(빈검증)
        • Bean Validation(빈검증) 보충자료
      • 13 예외처리
        • 예외처리 보충자료
      • 14 타입변환
      • 15 JDBC(Java Database Connectivity)
      • 16 커넥션풀
      • 17 트랜잭션
        • 트랜잭션 보충자료
      • 18 JDBC 템플릿 활용
      • 19 MyBatis
      • 20 JPA(Java Persistence API)
      • 22 게시판 프로젝트 실습
    • Spring Security
      • 보안(Security)
      • Spring Security
      • 2. Spring Security 알아보기
        • 보안 위협 실제 사례와 방어 전략
      • 3. Spring Security 기본 동작 흐름
      • 4. Spring Security로 인증 권한 추가하기
        • Spring Security의 인증 및 인가
      • 5. Spring Security에서 세션 관리하기
        • 세션(Session)과 쿠키(Cookie) 비교, 토큰(Token)과의 관계
        • 해싱 및 해싱알고리즘
        • base64
      • 6. Spring Security 악용 보호
        • SameSite
      • 7. Spring Security로 인가 권한 추가하기
      • 8. Bcrypt(비크립트) 암호화
      • OAuth2 적용하기
  • 네트워크
    • HTTP
    • OSI 7계층
  • DB&SQL
    • 01 Database(데이터베이스)와 SQL 개요
    • 02 관계형 모델
    • 03 집합
    • 04 JOIN 연산
    • 05 MySQL
      • 세이브포인트
      • DBeaver, Mysql 오토커밋 설정 관련
    • 06 SQL 기초
      • 예시데이터 쿼리문
    • 07 SQL 실습
      • 실습 스키마
    • 08 Join 활용
      • 실습스키마
    • 09 SQL 활용
      • 실습스키마
    • 10 정규화
      • 실습 스키마
    • 데이터타입
    • 예시 프로젝트 스키마 구성
  • AWS
    • SSL 연결하기
    • 보충설명
Powered by GitBook
On this page
  1. 스프링
  2. Spring Boot

15 JDBC(Java Database Connectivity)

p255 - build.gradle

plugins {
	id 'java'
	id 'org.springframework.boot' version '3.3.4'
	id 'io.spring.dependency-management' version '1.1.6'
}

group = 'spring'
version = '0.0.1-SNAPSHOT'

java {
	toolchain {
		languageVersion = JavaLanguageVersion.of(21)
	}
}

configurations {
	compileOnly {
		extendsFrom annotationProcessor
	}
}

repositories {
	mavenCentral()
}

dependencies {
	implementation 'org.springframework.boot:spring-boot-starter-jdbc'
	implementation 'org.springframework.boot:spring-boot-starter-web'
	testImplementation 'org.projectlombok:lombok'
	compileOnly 'org.projectlombok:lombok'
	runtimeOnly 'com.mysql:mysql-connector-j'
	annotationProcessor 'org.projectlombok:lombok'
	testImplementation 'org.springframework.boot:spring-boot-starter-test'
	testRuntimeOnly 'org.junit.platform:junit-platform-launcher'

	testCompileOnly 'org.projectlombok:lombok'
	testAnnotationProcessor 'org.projectlombok:lombok'
}

tasks.named('test') {
	useJUnitPlatform()
}

p258 - src/main/java/spring/jdbc/connection/DatabaseConnectionManager

public interface DatabaseConnectionManager {
    Connection getConnection() throws SQLException;

    void closeConnection(Connection connection);
}

p259 - src/main/java/spring/jdbc/connection/JdbcDatabaseConnectionManager

@Slf4j
public class JdbcDatabaseConnectionManager implements DatabaseConnectionManager{

    private static final String URL = "jdbc:mysql://localhost:3306/test";
    private static final String USERNAME = "root";
    private static final String PASSWORD = "1234";
    @Override
    public Connection getConnection() throws SQLException {
        try {
            Connection connection = DriverManager.getConnection(URL, USERNAME, PASSWORD);
            log.info("connection = {}", connection);
            return connection;
        } catch (SQLException e) {
            e.printStackTrace();
            throw e;
        }
    }

    @Override
    public void closeConnection(Connection connection) {
        if (connection != null) {
            try {
                connection.close();
                log.info("Connection closed.");
            } catch (SQLException e) {
                log.error("Failed to close connection", e);
            }
        }
    }
}

p260 - src/test/java/spring/jdbc/connection/JdbcDatabaseConnectionManagerTest

@Slf4j
class JdbcDatabaseConnectionManagerTest {
    private JdbcDatabaseConnectionManager connectionManager;

    @BeforeEach
    void setUp() {
        connectionManager = new JdbcDatabaseConnectionManager();
    }
    @Test
    void testGetConnection() {
        Connection connection = null;
        try {
            // 실제 데이터베이스에 연결 시도
            connection = connectionManager.getConnection();
            log.info("connection = {}", connection);
            assertNotNull(connection);
            assertFalse(connection.isClosed());
            log.info("Connection established successfully!");

        } catch (SQLException e) {
            fail("Connection failed: " + e.getMessage());
        } finally {
            // 연결 닫기
            if (connection != null) {
                connectionManager.closeConnection(connection);
            }
        }
    }
}

p262 - src/main/java/spring/jdbc/domain/Users

@Data
public class Users {

    private String userId;
    private String userName;
    private int age;
}

p263, 264, 266, 273 - src/main/java/spring/jdbc/repository/UsersRepository

@Slf4j
public class UsersRepository {

    private final JdbcDatabaseConnectionManager connectionManager;

    public UsersRepository(JdbcDatabaseConnectionManager connectionManager) {
        this.connectionManager = connectionManager;
    }
    public Users save(Users user) {
        String sql = "INSERT INTO users (userId, userName, age) VALUES (?, ?, ?)";

        Connection con = null;
        PreparedStatement pstmt = null;

        try {
            // 데이터베이스 연결
            con = connectionManager.getConnection();

            // PreparedStatement 생성
            pstmt = con.prepareStatement(sql);

            // PreparedStatement 파라미터 설정
            pstmt.setString(1, user.getUserId());
            pstmt.setString(2, user.getUserName());
            pstmt.setInt(3, user.getAge());

            // 쿼리 실행
            int affectedRows = pstmt.executeUpdate();
            log.info("affectedRows = {}", affectedRows);
            return user;

        } catch (SQLException e) {
            log.error("Failed to save user: {}", e.getMessage());
            throw new RuntimeException("Failed to save user", e);
        } finally {
            // 자원 해제
            try {
                if (pstmt != null) {
                    pstmt.close();
                }
                if (con != null) {
                    connectionManager.closeConnection(con);
                }
            } catch (SQLException e) {
                log.error("Failed to close resources", e);
            }
        }
    }

    // 사용자 조회 로직 (findById)
    public Users findById(String userId) {
        String sql = "SELECT * FROM users WHERE userId = ?";

        Connection con = null;
        PreparedStatement pstmt = null;
        ResultSet rs = null;

        try {
            // 데이터베이스 연결
            con = connectionManager.getConnection();

            // PreparedStatement 생성
            pstmt = con.prepareStatement(sql);
            pstmt.setString(1, userId);

            // 쿼리 실행 및 결과 처리
            rs = pstmt.executeQuery();

            if (rs.next()) {
                Users user = new Users();
                user.setUserId(rs.getString("userId"));
                user.setUserName(rs.getString("userName"));
                user.setAge(rs.getInt("age"));
                log.info("Found user: {}", user);
                return user;
            } else {
                log.warn("User with ID {} not found", userId);
                return null;
            }
        } catch (SQLException e) {
            log.error("Failed to find user: {}", e.getMessage());
            throw new RuntimeException("Failed to find user", e);
        } finally {
            // 자원 해제
            try {
                if (rs != null) {
                    rs.close();
                }
                if (pstmt != null) {
                    pstmt.close();
                }
                if (con != null) {
                    connectionManager.closeConnection(con);
                }
            } catch (SQLException e) {
                log.error("Failed to close resources", e);
            }
        }
    }

    // 사용자 업데이트 로직 (update)
    public Users update(Users user) {
        String sql = "UPDATE users SET userName = ?, age = ? WHERE userId = ?";

        Connection con = null;
        PreparedStatement pstmt = null;

        try {
            // 데이터베이스 연결
            con = connectionManager.getConnection();

            // PreparedStatement 생성
            pstmt = con.prepareStatement(sql);

            // PreparedStatement 파라미터 설정
            pstmt.setString(1, user.getUserName());
            pstmt.setInt(2, user.getAge());
            pstmt.setString(3, user.getUserId());

            // 쿼리 실행
            int affectedRows = pstmt.executeUpdate();
            log.info("Updated affectedRows = {}", affectedRows);

            if (affectedRows > 0) {
                log.info("User updated successfully: {}", user.getUserId());
                return user;
            } else {
                log.warn("No user found with ID {}", user.getUserId());
                return null;
            }

        } catch (SQLException e) {
            log.error("Failed to update user: {}", e.getMessage());
            throw new RuntimeException("Failed to update user", e);
        } finally {
            // 자원 해제
            try {
                if (pstmt != null) {
                    pstmt.close();
                }
                if (con != null) {
                    connectionManager.closeConnection(con);
                }
            } catch (SQLException e) {
                log.error("Failed to close resources", e);
            }
        }
    }

    // 사용자 삭제 로직 (deleteById)
    public void deleteById(String userId) {
        String sql = "DELETE FROM users WHERE userId = ?";

        Connection con = null;
        PreparedStatement pstmt = null;

        try {
            // 데이터베이스 연결
            con = connectionManager.getConnection();

            // PreparedStatement 생성
            pstmt = con.prepareStatement(sql);
            pstmt.setString(1, userId);

            // 쿼리 실행
            int affectedRows = pstmt.executeUpdate();
            log.info("Deleted affectedRows = {}", affectedRows);

            if (affectedRows > 0) {
                log.info("User with ID {} deleted successfully", userId);
            } else {
                log.warn("No user found with ID {}", userId);
            }

        } catch (SQLException e) {
            log.error("Failed to delete user: {}", e.getMessage());
            throw new RuntimeException("Failed to delete user", e);
        } finally {
            // 자원 해제
            try {
                if (pstmt != null) {
                    pstmt.close();
                }
                if (con != null) {
                    connectionManager.closeConnection(con);
                }
            } catch (SQLException e) {
                log.error("Failed to close resources", e);
            }
        }
    }
}

p265, 269, 270, 271, 272, 274 - src/test/java/spring/jdbc/repository/UsersRepositoryTest

@Slf4j
class UsersRepositoryTest {

    private UsersRepository usersRepository;
    private JdbcDatabaseConnectionManager connectionManager;

    @BeforeEach
    void setUp() throws SQLException {
        // 테스트용 DB에 연결
        connectionManager = new JdbcDatabaseConnectionManager();
        usersRepository = new UsersRepository(connectionManager);
        try (Connection connection = connectionManager.getConnection();
             Statement stmt = connection.createStatement()) {
            stmt.executeUpdate("DELETE FROM users");
            stmt.executeUpdate("ALTER TABLE users AUTO_INCREMENT = 1"); // AUTO_INCREMENT 초기화
        }
    }

    @Test
    void testSaveUser() {
        // 테스트용 유저 생성
        Users user = new Users();
        user.setUserId("AT001");
        user.setUserName("JohnDoe");
        user.setAge(30);

        // 유저 저장 테스트
        Users savedUser = usersRepository.save(user);

        // 저장된 유저의 정보 확인
        assertNotNull(savedUser);
        assertEquals("AT001", savedUser.getUserId());
        assertEquals("JohnDoe", savedUser.getUserName());
        assertEquals(30, savedUser.getAge());

        log.info("User saved successfully: " + savedUser.getUserName());
    }

    @Test
    void testFindUserById() {
        // 먼저 사용자 저장
        Users user = new Users();
        user.setUserId("AT001");
        user.setUserName("JaneDoe");
        user.setAge(25);
        Users savedUser = usersRepository.save(user);

        // 저장된 사용자의 ID로 조회 테스트
        Users foundUser = usersRepository.findById(String.valueOf(savedUser.getUserId()));

        log.info("savedUser = {}", savedUser);
        log.info("foundUser = {}", foundUser);

        // 조회된 사용자 정보 확인
        assertNotNull(foundUser);
        assertEquals("AT001", foundUser.getUserId());
        assertEquals("JaneDoe", foundUser.getUserName());
        assertEquals(25, foundUser.getAge());

        log.info("User found successfully: " + foundUser.getUserName());
    }

    @Test
    void testFindUserByIdNotFound() {
        // 존재하지 않는 ID로 조회 테스트
        Users foundUser = usersRepository.findById("999");

        // 조회 결과가 null인지 확인
        assertNull(foundUser);

        log.info("User with ID 999 not found");
    }

    @Test
    void testUpdateUser() {
        // 먼저 사용자 저장
        Users user = new Users();
        user.setUserId("AT002");
        user.setUserName("JaneDoe");
        user.setAge(25);
        Users savedUser = usersRepository.save(user);

        // 수정할 사용자 정보 설정
        savedUser.setUserName("JaneUpdated");
        savedUser.setAge(28);

        // 사용자 정보 수정
        Users updatedUser = usersRepository.update(savedUser);

        // 수정된 사용자 정보 확인
        assertNotNull(updatedUser);
        assertEquals("JaneUpdated", updatedUser.getUserName());
        assertEquals(28, updatedUser.getAge());

        log.info("User updated successfully: " + updatedUser.getUserName());
    }

    @Test
    void testDeleteUser() {
        // 먼저 사용자 저장
        Users user = new Users();
        user.setUserId("AT003");
        user.setUserName("JohnToDelete");
        user.setAge(40);
        Users savedUser = usersRepository.save(user);

        // 사용자 삭제
        usersRepository.deleteById(savedUser.getUserId());

        // 삭제된 사용자가 없는지 확인
        Users deletedUser = usersRepository.findById(savedUser.getUserId());
        assertNull(deletedUser);

        log.info("User deleted successfully: " + savedUser.getUserName());
    }
}

Previous14 타입변환Next16 커넥션풀

Last updated 6 months ago