Skip to Content
Suffering builds character
아카이브14.데이터베이스SQL3.JDBC6. DataSource 인터페이스

6. DataSource 인터페이스

1.DataSource interface

A factory for connections to the physical data source that this DataSource object represents. An alternative to the DriverManager facility, a DataSource object is the preferred means of getting a connection. An object that implements the DataSource interface will typically be registered with a naming service based on the Java™ Naming and Directory (JNDI) API.

데이터베이스 커넥션을 얻기 위한 방법은 기본적으로 DriverManager 를 통해 수행됨

JDBC.java
DriverManager.getConnection(DB_URL, USER, PASSWORD);

매 요청 시 마다 커넥션을 생성하는 처리 시간을 단축하기 위해 고안된 커넥션 풀을 적용하려면, 일반적으로 커넥션 풀 메커니즘을 구현한 외부 라이브러리를 활용함

Vendor 종류
ex) Apache DBCP, HikariCP

로깅 라이브러리에서도 Log4j, Logback을 SLF4j 인터페이스를 통해 애플리케이션 코드와 구현체 간의 결합도를 낮춘 것처럼,

커넥션 풀도 마찬가지로 각각의 구현체들을 추상화시킨 DataSource라는 인터페이스를 통해 코드를 작성해둘 경우, 추후 간편하게 구현체만 변경하여 빠르게 교체가 가능

JPA에서도 Hibernate를 구현체로 사용했지만, 인터페이스 자체는 javax.persistence 패키지인 JPA 인터페이스(JPA 명세)로 사용함으로써 애플리케이션 코드와 구현체 간의 결합도를 낮춤

정리하면, DataSource란 애플리케이션 내 코드를 최소한으로 수정하면서 편리하게 교체가 가능하도록 지원하는 DB 커넥션 연결용 인터페이스
→ 스프링에서도 활용됨

따라서 DataSource 인터페이스는 커넥션을 획득하기 위한 메서드인 getConnection( )를 정의해두었음

javax.sql.DataSource interface 내부 코드

DataSource.java
public interface DataSource extends CommonDataSource, Wrapper { /** * <p>Attempts to establish a connection with the data source that * this {@code DataSource} object represents. * * @return a connection to the data source * @throws SQLException if a database access error occurs * @throws java.sql.SQLTimeoutException when the driver has determined that the * timeout value specified by the {@code setLoginTimeout} method * has been exceeded and has at least tried to cancel the * current database connection attempt */ Connection getConnection() throws SQLException; // and more... }
Last updated on