모아이티

[게시판 만들기] 코드로 배우는 스프링 웹 프로젝트 Part1 - JDBC 연결 & Hikari CP 커넥션 풀 설정 본문

Spring 게시판 만들기

[게시판 만들기] 코드로 배우는 스프링 웹 프로젝트 Part1 - JDBC 연결 & Hikari CP 커넥션 풀 설정

Yun's kitchen 2021. 3. 2. 22:05

JDBC 연결

JDBC 연결을 하려면 JDBC 드라이버가 필요합니다.

 

https://mvnrepository.com/artifact/com.oracle.database.jdbc/ojdbc6/11.2.0.4

 

Maven Repository: com.oracle.database.jdbc » ojdbc6 » 11.2.0.4

 

mvnrepository.com

<!-- https://mvnrepository.com/artifact/com.oracle.database.jdbc/ojdbc6 -->
<dependency>
    <groupId>com.oracle.database.jdbc</groupId>
    <artifactId>ojdbc6</artifactId>
    <version>11.2.0.4</version>
</dependency>

pom.xml에 추가 후 update project 항상 dependency 추가 한 다음에는 거쳐야 할 과정이다!

테스트코드를 거쳐서 확인을 꼭 해준다.

 

org.zerock.persistence 패키지에 JDBCTests 클래스를 만들어 준다.

 

package org.zerock.persistence;

import java.sql.Connection;
import java.sql.DriverManager;

import org.junit.Test;

import lombok.extern.log4j.Log4j;

@Log4j
public class JDBCTests {

	@Test
	public void testConnection() throws Exception {
		
		Class cls = Class.forName("oracle.jdbc.driver.OracleDriver"); //이 부분은 항상 복사 붙여넣기 할 것
		
		Connection con = DriverManager.getConnection(
				"jdbc:oracle:thin:@localhost:1521:orcl",
				"board","board");
		
		log.info(con);
		
		con.close(); //bad code
	}
	
}

 

데이터베이스 연결이 가능하면 정상적으로 데이터 베이스가 연결 된 걸 확인할 수 있습니다.

SQL Developer에서 설정한 사용자이름과 비밀번호 맞게 써주세요.

 


HikariCP 커넥션 풀 설정

https://mvnrepository.com/artifact/com.zaxxer/HikariCP/3.4.5

 

Maven Repository: com.zaxxer » HikariCP » 3.4.5

 

mvnrepository.com

DataSource 설정

java에서는 DateSource라는 인터페이스를 통해  커넥션 풀을 사용하고 DataSource를 통해 매번 데이터베이스와 연결하는 방식이 아니라 미리 연결을 맺어주고 반환하는 구조를 이용합니다.

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xmlns:context="http://www.springframework.org/schema/context"
	xsi:schemaLocation="http://www.springframework.org/schema/beans https://www.springframework.org/schema/beans/spring-beans.xsd
		http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.3.xsd">
	
	<!-- Root Context: defines shared resources visible to all other web components -->
		
		<!-- hikariConfig 설정 -->
		<bean id="hikariConfig" class="com.zaxxer.hikari.HikariConfig">
			<property name="driverClassName" value="oracle.jdbc.driver.OracleDriver"></property>
			<property name="jdbcUrl" value="jdbc:oracle:thin:@localhost:1521:orcl"></property>
			<property name="username" value="board"></property>
			<property name="password" value="board"></property>
		</bean>
		
		<!-- dateSource 설정 -->
		<bean id="dataSource" class="com.zaxxer.hikari.HikariDataSource" destroy-method="close">
			<constructor-arg ref="hikariConfig"></constructor-arg>
		</bean>
		
		<context:component-scan base-package="org.zerock.sample"></context:component-scan>
		
</beans>

root-context.xml에 추가하기

 

Test 코드 작성

DataSourceTests.java

package org.zerock.persistence;

import java.sql.Connection;

import javax.sql.DataSource;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

import lombok.extern.log4j.Log4j;

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("file:src/main/webapp/WEB-INF/spring/root-context.xml")
@Log4j
public class DataSourceTests {

	@Autowired
	private DataSource ds;
	
	@Test
	public void testConnection() {
		try(Connection con = ds.getConnection()){
			log.info(con);
		}catch (Exception e) {
			log.error(e.getMessage());
		}
	}
}

출처

- 코드로 배우는 스프링 웹 프로젝트(책)
- Youtube 구멍가게 코딩단 

Comments