# Spring Boot JDBC

## Spring Boot JDBC

{% embed url="<https://spring.io/projects/spring-data-jdbc>" %}
공식 문서
{% endembed %}

Spring Boot JDBC를 사용하기 위해서는 다음과 같은 의존성이 필요하다.

* org.springframework.boot spring-boot-starter-jdbc&#x20;
* com.oracle.database.jdbc ojdbc8

빌드 프레임워크에 따라 다음과 같이 추가하거나 프로젝트 생성 화면에서 설정한다.

<mark style="color:red;">`spring-boot-starter-jdbc`</mark>를 설정할 경우 다음과 같이 종속된 의존성이 추가된다.

<details>

<summary>spring-boot-starter-jdbc</summary>

* spring-boot-starter
* HikariCP
  * slf4j-api
* spring-jdbc
  * spring-beans
  * spring-core
  * spring-tx
    * spring-beans
    * spring-core

</details>

## 프로젝트 생성

<mark style="color:blue;">`boot05jdbc`</mark> 프로젝트를 생성한다.

### 프로젝트 정보 입력

<div align="left"><figure><img src="/files/7Ia3mDItVZ59yez8bxyr" alt=""><figcaption><p>프로젝트 정보</p></figcaption></figure> <figure><img src="/files/6jGogEh8Bfti7LziZxCh" alt=""><figcaption><p>의존성 정보</p></figcaption></figure></div>

### Maven일 경우 추가되는 항목

```markup
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-jdbc</artifactId>
</dependency>

<dependency>
    <groupId>com.oracle.database.jdbc</groupId>
    <artifactId>ojdbc8</artifactId>
    <scope>runtime</scope>
</dependency>
```

### Gradle일 경우 추가되는 항목

```groovy
implementation group: 'org.springframework.boot', name: 'spring-boot-starter-jdbc', version: '2.7.3'
implementation group: 'com.oracle.database.jdbc', name: 'ojdbc8', version: '21.7.0.0'
```

## 기본 설정 사용

Spring Boot에서는 제공되는 설정을 통해 JDBC 설정을 수행할 수 있다.&#x20;

### application.properties

{% code title="application.properties" %}

```properties
spring.datasource.driver-class-name=oracle.jdbc.OracleDriver
spring.datasource.url=jdbc:oracle:thin:@localhost:1521:xe
spring.datasource.username=hacademy
spring.datasource.password=hacademy
```

{% endcode %}

## Configuration 생성

제공되는 설정 외 직접 구현하고 싶은 경우에는 <mark style="color:red;">`@Configuration`</mark> 을 생성하여 도구를 직접 등록할 수 있다.

### Package 생성

<div align="left"><figure><img src="/files/ejqxj4MObR5V5diJkWhb" alt=""><figcaption></figcaption></figure></div>

### Configuration class 생성

생성한 패키지 내부에 <mark style="color:blue;">`DatabaseConfiguration`</mark>이라는 이름으로 클래스를 작성한다.

<div align="left"><figure><img src="/files/nlkXKH47lrtKbcSC6Ox9" alt=""><figcaption></figcaption></figure></div>

### Bean 생성

Configuration 내부에 <mark style="color:red;">`@Bean`</mark> 생성 코드를 작성한다.&#x20;

```java
@Bean
public DriverManagerDataSource dataSource() {
	DriverManagerDataSource dataSource = new DriverManagerDataSource();
	dataSource.setDriverClassName("oracle.jdbc.OracleDriver");
	dataSource.setUrl("jdbc:oracle:thin:@localhost:1521:xe");
	dataSource.setUsername("hacademy");
	dataSource.setPassword("hacademy");
	return dataSource;
}

@Bean
public JdbcTemplate jdbcTemplate(DataSource dataSource) {
	JdbcTemplate jdbcTemplate = new JdbcTemplate(dataSource);
	return jdbcTemplate;
}
```

생성된 Bean은 Spring에서 자체적으로 Component scan을 통하여 Spring Container에 등록하므로 프로젝트 내 어디서든 사용 가능하다. 또한 Bean 생성 시 매개변수로 선언된 항목들은 Spring에서 가능한 요소를 찾아서 **주입(Injection)** 처리한다.

{% hint style="info" %}
Configuration 생성 시 주의사항

package의 경우 프로젝트 생성 시 입력하는 기본 패키지이거나 그 하위 패키지여야 한다. 만약 해당 패키지가 아닐 경우에는 별도로 <mark style="color:red;">`@ComponentScan`</mark>을 추가해야 한다.

```java
@ComponentScan("탐색할패키지이름")
@SpringBootApplication
public class Boot05jdbcApplication {
	public static void main(String[] args) {
		SpringApplication.run(Boot05jdbcApplication.class, args);
	}
}
```

{% endhint %}

## 등록된 Bean 확인

[Spring Actuator](/web/back-end/spring-boot/spring-controller/spring-actuator.md)를 통해 등록된 Bean을 확인할 수 있다. 위의 두 가지 방법 중 하나를 사용하여 등록하였다면 다음과 같이 등록된 bean에서 찾을 수 있다. 이 문서에서는 [#configuration](#configuration "mention")방식으로 구현하였다.

<div align="left"><figure><img src="/files/ca8cDhkeKUDkXPV8M5gB" alt=""><figcaption><p>spring boot dashboard - show properties</p></figcaption></figure></div>

## Bean 사용

등록이 완료된 Bean은 다음과 같은 Annotation으로 사용할 수 있다.

* <mark style="color:red;">`@Autowired`</mark> - 일치하는 타입의 대상을 찾아 주입하는 Annotation
* <mark style="color:red;">`@Qualifier`</mark> - <mark style="color:red;">`@Autowired`</mark>와 같이 사용하여 대상의 식별 ID를 사용하여 주입하는 Annotation

원하는 클래스 내부에 다음과 같이 필드를 선언하여 사용한다.

```java
@Autowired
private JdbcTemplate jdbcTemplate;
```

<mark style="color:red;">`@Qualifier`</mark>와 같이 사용할 경우는 다음과 같이 작성한다.

```java
@Autowired @Qualifier("jdbcTemplate")
private JdbcTemplate jdbcTemplate;
```

일반적으로 <mark style="color:red;">`@Qualifier`</mark>는  동일한 타입의 객체가 두 개 이상이어서 <mark style="color:red;">`@Autowired`</mark>만으로 식별이 불가능한 상황일 경우 사용한다.


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://docs.sysout.co.kr/web/back-end/spring-boot/spring-boot-jdbc.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
