-
DB 연결 시, 특정 객체만 close() 하는 이유Spring Boot/DB 2022. 1. 11. 19:09
코드를 보던 중에 스프링 부트와 디비를 직접 연결하는 경우에는 꼭 연결했다가 해제해주는 것을 보았다.
한번 연결해 놓으면 될 것 같은데 왜 API 기능을 수행할 때마다 연결/해제를 반복해야 하는 걸까?
1) 운영체제가 외부 파일을 "열면" 다른 프로세스가 접근 못하도록 잠금을 하기 때문.
DB가 계속 연결 중이면, API가 접근 할때 제약이 있을 수 있어 x.close()로 사용마다 연결을 끊어주어야 한다.
When a file is "opened," the OS marks the file as locked, generally so it can't be deleted by other processes while it's being used. x.close() undoes the lock, allowing the OS and other processes to do what it wishes with the file.
2) 객체의 경우 JVM이 가비지 컬렉터 기능이 메모리에 정리를 해주지만, 시스템 자원은 객체가 아니므로 x.close()로 직접 메모리를 정리해주어야 한다. 시스템 자원에는 DB커넥션, 네트워크 커넥션, 쓰레드 등이 있다.
// DB 연결 Connection connection = DriverManager.getConnection("jdbc:h2:mem:springcoredb", "sa", ""); // DB Query 작성 및 실행 Statement stmt = connection.createStatement(); ResultSet rs = stmt.executeQuery("select * from product"); // DB Query 결과를 상품 객체 리스트로 변환 while (rs.next()) { Product product = new Product(); product.setId(rs.getLong("id")); product.setImage(rs.getString("image")); product.setLink(rs.getString("link")); product.setLprice(rs.getInt("lprice")); product.setMyprice(rs.getInt("myprice")); product.setTitle(rs.getString("title")); products.add(product); } // DB 연결 해제 rs.close(); connection.close();
출처!
반응형'Spring Boot > DB' 카테고리의 다른 글
[M1 Mac] Mysql 명령어 정리 (+ docker로 설치) (0) 2023.06.27 [SQL] Or 와 In 조건 뭐가 더 좋을까? SELECT OR vs IN, which is better performance. (0) 2022.07.15 Flyway로 데이터베이스 마이그레이션 해보자 (이론편) (0) 2022.07.14 [Mybatis 시리즈 2] DataSouce와 DBCP (DataBase Connection Pool) (0) 2022.04.14 [Mybatis 시리즈 1] 동작 원리와 스프링에서 어떻게 사용될까? (0) 2022.04.14