스프링과 mySql 연결하기
maven repository
spring-jdbc, mysql-connector-java 찾아서 pom.xml에 dependency로 넣고 메이븐 업데이트
<!-- https://mvnrepository.com/artifact/org.springframework/spring-jdbc -->
<!-- https://mvnrepository.com/artifact/mysql/mysql-connector-java -->
* spring-jdbc의 버전 <properties>의 스프링 버전과 동일하게 하기위해
<version>${org.springframework-version}</version>으로 변경한다.
* JUnit 테스트 사용하기위해 버전 4.12로 수정(4.12이상이어야 가능)
root-context.xml에 DB관련 빈 등록
<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="com.mysql.jdbc.Driver"></property>
<property name="url" value="jdbc:mysql://localhost:3306/springbaic?useUnicode=true&characterEncoding=utf8"></property>
<property name="username" value="suyeon"></property>
<property name="password" value="1234"></property>
</bean>
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.GenericXmlApplicationContext;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import javax.sql.DataSource;
import java.sql.Connection;
import static org.junit.Assert.*;
@RunWith(SpringJUnit4ClassRunner.class) //ac 자동으로 만들고
@ContextConfiguration(locations = {"file:src/main/webapp/WEB-INF/spring/**/root-context.xml"}) // 이걸로 ac 설정
public class DBConnectionTest2Test{
@Autowired
DataSource ds; // getBean안할 수 있음
@Test //JUnit으로 테스트할 메소드를 뜻함
public void springJdbcConnectionTest() throws Exception {
// ApplicationContext ac = new GenericXmlApplicationContext("file:src/main/webapp/WEB-INF/spring/**/root-context.xml");
// DataSource ds = ac.getBean(DataSource.class);
Connection conn = ds.getConnection(); // 데이터베이스의 연결을 얻는다.
System.out.println("conn = " + conn);
assertTrue(conn!=null); // 괄호 안의 조건식이 true면, 테스트 성공, 아니면 실패(JUnit 테스트 부분)
}
}
댓글