DBCP(DataBase Connection Pool)
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-dbcp2</artifactId>
<version>2.7.0</version>
</dependency>
src/main/webapp/WEB-INF/spring/root-context.xml
<bean id="dataSource" class="org.apache.commons.dbcp2.BasicDataSource">
<property name="driverClassName" value="oracle.jdbc.OracleDriver"></property>
<property name="url" value="jdbc:oracle:thin:@localhost:1521:xe"></property>
<property name="username" value="test"></property>
<property name="password" value="test"></property>
<property name="maxTotal" value="20"></property>
<property name="maxIdle" value="10"></property>
<property name="maxWaitMillis" value="3000"></property>
</bean>
<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="oracle.jdbc.OracleDriver"></property>
<property name="url" value="jdbc:oracle:thin:@localhost:1521:xe"></property>
<property name="username" value="test"></property>
<property name="password" value="test"></property>
</bean>
추가된 항목은 다음과 같다.
<bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
<property name="dataSource" ref="dataSource"></property>
</bean>
다른 코드들은 기존의 JDBC와 다르지 않기 때문에 select 구문만 수행하여 연결이 정상적으로 이루어지는지 확인한다.
src/test/java : com.hakademy.spring13.Test01
package com.hakademy.spring13;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.web.WebAppConfiguration;
@RunWith(SpringJUnit4ClassRunner.class)
@WebAppConfiguration
@ContextConfiguration(locations = {
"file:src/main/webapp/WEB-INF/spring/root-context.xml",
"file:src/main/webapp/WEB-INF/spring/appServlet/servlet-context.xml"
})
public class Test01 {
@Autowired
private JdbcTemplate jdbcTemplate;
@Test
public void selectCount() {
String sql = "select count(*) from student";
int count = jdbcTemplate.queryForObject(sql, Integer.class);
System.out.println("count = "+count);
}
}