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

16 커넥션풀

p283 - src/test/java/spring/jdbc/connection/DataSourceTest

@Slf4j
public class DataSourceTest {

    private static final String URL = "jdbc:mysql://localhost:3306/test";
    private static final String USERNAME = "root";
    private static final String PASSWORD = "1234";

    @Test
    void dataSourceTest() throws SQLException {
        DriverManagerDataSource datasource = new DriverManagerDataSource(URL, USERNAME, PASSWORD);
        getConnection(datasource);
    }

    @Test
    void hikariCPDataSourceTest() throws SQLException, InterruptedException {
        // HikariCP DataSource 생성
        HikariDataSource dataSource = new HikariDataSource();
        dataSource.setJdbcUrl(URL);
        dataSource.setUsername(USERNAME);
        dataSource.setPassword(PASSWORD);
        dataSource.setMaximumPoolSize(10);
        dataSource.setPoolName("HikariPool");
        dataSource.setInitializationFailTimeout(5000);
        getConnection(dataSource);
        Thread.sleep(1000);
    }

    private void getConnection(DataSource dataSource) throws SQLException {
        Connection con1 = dataSource.getConnection();
        Connection con2 = dataSource.getConnection();
        log.info("con = {}", con1);
        log.info("con2 = {}", con2);
    }
}

p284 - src/main/resources/logback.xml

<configuration>
    <appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
        <encoder>
            <pattern>%d{yyyy-MM-dd HH:mm:ss} [%thread] %-5level %logger{36} - %msg%n</pattern>
        </encoder>
    </appender>

    <root level="INFO">
        <appender-ref ref="STDOUT" />
    </root>

    <!-- HikariCP의 디버그 레벨 설정 -->
    <logger name="com.zaxxer.hikari" level="DEBUG"/>
</configuration>

p286 - src/main/java/spring/jdbc/repository/UsersDataSourceRepository

@Slf4j
public class UsersDataSourceRepository {

    private final DataSource dataSource;

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

        Connection con = null;
        PreparedStatement pstmt = null;

        try {
            // 데이터베이스 연결
            con = dataSource.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) {
                    con.close();
                }
            } 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 = dataSource.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) {
                    con.close();
                }
            } 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 = dataSource.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) {
                    con.close();
                }
            } 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 = dataSource.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) {
                    con.close();
                }
            } catch (SQLException e) {
                log.error("Failed to close resources", e);
            }
        }
    }
}

p287 - src/test/java/spring/jdbc/repository/UsersDataSourceRepositoryTest

@Slf4j
public class UsersDataSourceRepositoryTest {

    private UsersDataSourceRepository usersRepository;
    private DataSource dataSource;

    @BeforeEach
    void setUp() throws SQLException {
        // MySQL 데이터베이스에 연결
//        dataSource = new DriverManagerDataSource(
//                "jdbc:mysql://localhost:3306/test", // MySQL 연결 URL (스키마: test)
//                "root",                             // MySQL 사용자명
//                "1234"                        // MySQL 비밀번호
//        );

        HikariDataSource dataSource = new HikariDataSource();
        dataSource.setJdbcUrl("jdbc:mysql://localhost:3306/test");
        dataSource.setUsername("root");
        dataSource.setPassword("1234");


        usersRepository = new UsersDataSourceRepository(dataSource);

        // 테스트용 테이블 생성
        try (Connection connection = dataSource.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("user1");
        user.setUserName("JohnDoe");
        user.setAge(30);

        Users savedUser = usersRepository.save(user);

        // 저장된 사용자 확인
        assertNotNull(savedUser);
        assertEquals("JohnDoe", savedUser.getUserName());
        assertEquals(30, savedUser.getAge());
    }

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

        // 저장된 사용자를 조회
        Users foundUser = usersRepository.findById("user2");

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

    @Test
    void testUpdateUser() {
        // 사용자 저장
        Users user = new Users();
        user.setUserId("user3");
        user.setUserName("InitialName");
        user.setAge(20);
        usersRepository.save(user);

        // 사용자 정보 수정
        user.setUserName("UpdatedName");
        user.setAge(22);
        Users updatedUser = usersRepository.update(user);

        // 수정된 사용자 확인
        assertNotNull(updatedUser);
        assertEquals("UpdatedName", updatedUser.getUserName());
        assertEquals(22, updatedUser.getAge());
    }

    @Test
    void testDeleteUser() {
        // 사용자 저장
        Users user = new Users();
        user.setUserId("user4");
        user.setUserName("UserToDelete");
        user.setAge(35);
        usersRepository.save(user);

        // 사용자 삭제
        usersRepository.deleteById("user4");

        // 삭제 후 사용자 확인
        Users deletedUser = usersRepository.findById("user4");
        assertNull(deletedUser); // 삭제된 사용자는 조회되지 않아야 함
    }
}
Previous15 JDBC(Java Database Connectivity)Next17 트랜잭션

Last updated 6 months ago