Spring 에서 DB 접속하는 방법에 대한 개념 정리
코드로 배우는 스프링 웹프로젝트 라는 책을 보고 있다. 쉽게 써진 책이고 스프링의 기술적 설명을 최소화한 상태로 진행하도록 구성되어 있어 초보가 보기에 참 좋은 책인 듯 하다.
Spring에서 DB에 접속을 하는 코드를 이해하려면 아래 내용을 알고 있어야 한다.
1. JDBC 만을 이용한 접속 테스트
pom.xml
1
2
3
4
5
6
|
<!-- MySQL connector/j -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.39</version>
</dependency>
|
cs |
위와 같이 작성하여 JDBC를 사용하기 위한 driver를 다운로드한다.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
|
public class MySQLConnectionTest {
private static final String DRIVER = "com.mysql.jdbc.Driver";
private static final String URL = "jdbc:mysql://127.0.0.1:3306/repacat_schema";
private static final String USER = "repacat";
private static final String PW = "repacat";
@Test
public void testConnection() throws Exception {
Class.forName(DRIVER);
try(Connection conn = DriverManager.getConnection(URL, USER, PW)) {
System.out.println(conn);
} catch(Exception e) {
e.printStackTrace();
}
}
}
|
cs |
Class.forName 으로 드라이버를 로드하고 커넥션을 만들 수 있다.
2. Spring 에서 dataSource 를 정의하고 이를 통한 접속 테스트
pom.xml
1
2
3
4
5
6
|
<!-- spring-jdbc : jdbc 프로그래밍하면서 개발하기 지루한 부분을 spring이 대신 해줌 -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>${org.springframework-version}</version>
</dependency>
|
cs |
root-context.xml
1
2
3
4
5
6
7
|
<!-- dataSource 설정, spring-jdbc 모듈 사용, spring 에서 jdbc 를 통해 mysql 에 접속할 수 있게 함 -->
<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="com.mysql.jdbc.Driver"></property>
<property name="url" value="jdbc:mysql://127.0.0.1:3306/repacat_schema"></property>
<property name="username" value="repacat"></property>
<property name="password" value="repacat"></property>
</bean>
|
cs |
root-context.xml 에 dataSource bean 을 선언하여 DI 받을 수 있도록 설정한다. dataSource bean 은 spring-jdbc 모듈에 있는 클래스(org.springframework.jdbc.datasource.DriverManagerDataSource)를 이용하여 JDBC 드라이버를 통해 MySQL 서버에 접속할 수 있게한다.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
|
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations={"file:src/main/webapp/WEB-INF/spring/**/*.xml"})
public class DataSourceTest {
@Inject
private DataSource ds;
@Test
public void testConnection() throws Exception {
try(Connection conn = ds.getConnection()) {
System.out.println(conn);
} catch(Exception e) {
e.printStackTrace();
}
}
}
|
cs |
dataSourrce 를 DI 받고 이를 통해 커넥션을 만들 수 있다.
3. Spring 에서 MyBatis 를 설정하고 이를 이용한 접속 테스트
pom.xml
1
2
3
4
5
6
7
8
9
10
11
|
<!-- Mybatis -->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.2.8</version>
</dependency>
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis-spring</artifactId>
<version>1.2.2</version>
</dependency>
|
cs |
MyBatis 를 사용하기 위해 위 두 모듈이 필요하다.
root-context.xml
1
2
3
4
5
6
|
<!-- mybatis 설정, mybatis-spring 모듈 사용 -->
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource" ref="dataSource"></property>
<!-- mybatis 용 config 파일을 로드하도록 설정 -->
<property name="configLocation" value="classpath:/mybatis-config.xml"></property>
</bean>
|
cs |
마찬가지로 root-context.xml 에 MyBatis 를 사용하기 위한 bean 을 선언하여 DI 받을 수 있도록 한다. Mybatis 설정에는 기존에 정의한 DataSource 가 사용된다. sqlSessionFactory 는 MyBatis 사용시 꼭 필요한 객체라고 한다.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
|
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations={"file:src/main/webapp/WEB-INF/spring/**/*.xml"})
public class MyBatisTest {
@Inject
private SqlSessionFactory sqlSessionFactory;
@Test
public void testFactory() {
System.out.println(sqlSessionFactory);
}
@Test
public void testSession() throws Exception {
try(SqlSession session = sqlSessionFactory.openSession()) {
System.out.println(session);
} catch(Exception e) {
e.printStackTrace();
}
}
}
|
cs |
SqlSessionFactory 를 통해 Session 을 얻을 수 있다.