티스토리 뷰

Study/Spring

[Spring] Mysql과 JUnit (2)

그징그징 2018. 12. 24. 16:17

[Spring] Mysql과 JUnit (2)


root-context.xml에 Mysql과 관련된 설정을 추가하고 JUnit으로 확인하겠습니다.





1. Java Mysql 기본 연동 코드


public class MysqlConnectionTest {


public static void main(String[] args) {


Connection con = null;

PreparedStatement pstmt = null;

ResultSet rs = null;

try {

Class.forName("com.mysql.cj.jdbc.Driver");

con = DriverManager.getConnection("jdbc:mysql://localhost:3306/?useSSL=false&serverTimezone=UTC", "root", "password");

pstmt = con.prepareStatement("select sysdate() from dual");

rs = pstmt.executeQuery();

while(rs.next())

System.out.println(rs.getString(1));

} catch (ClassNotFoundException e) {

// TODO Auto-generated catch block

e.printStackTrace();

} catch (SQLException e) {

// TODO Auto-generated catch block

e.printStackTrace();

}finally {

// Close Statement and Connection

if (pstmt != null) {

try {

pstmt.close();

} catch (SQLException e) {

// TODO Auto-generated catch block

e.printStackTrace();

}

}

if (con != null) {

try {

con.close();

} catch (SQLException e) {

// TODO Auto-generated catch block

e.printStackTrace();

}

}

}


}



src/main/java 디렉터리의 com.sora.shop 패키지안에

main 메소드가 포함된 클래스를 하나 생성했습니다.


해당 코드 작성 후 java application 으로 실행했을 때 


현재 시간이 출력되는 것을 확인할수있습니다.

(mysql - connector 버전을 6.0.6에서 8버전대로 수정했습니다.

java.sql.SQLException: Unknown system variable 'query_cache_size'

라는 error가 나서 버전을 올려야 연동이 됐습니다^.^;)




2. DataSource(Connection-pool) 


public class MysqlConnectionTest {


public static void main(String[] args) {

BasicDataSource dataSource = new BasicDataSource();

dataSource.setDriverClassName("com.mysql.cj.jdbc.Driver");

dataSource.setUrl("jdbc:mysql://localhost:3306/?useSSL=false&serverTimezone=UTC");

dataSource.setUsername("root");

dataSource.setPassword("password");

Connection con = null;

PreparedStatement pstmt = null;

ResultSet rs = null;

try {

con = dataSource.getConnection();

pstmt = con.prepareStatement("select sysdate() from dual");

rs = pstmt.executeQuery();

while(rs.next())

System.out.println(rs.getString(1));

} catch (SQLException e) {

// TODO Auto-generated catch block

e.printStackTrace();

} finally {

// Close Statement and Connection

if (pstmt != null) {

try {

pstmt.close();

} catch (SQLException e) {

// TODO Auto-generated catch block

e.printStackTrace();

}

}

if (con != null) {

try {

con.close();

} catch (SQLException e) {

// TODO Auto-generated catch block

e.printStackTrace();

}

}

}


}



Conneciton-Pool 연동을 위해 dataSource 객체를 생성해서 한 예제입니다.




3. root-context.xml 로 연동 설정 추가하기


집중해서 봐야할 부분은 2번의 굵은 글씨로 되어있는 부분입니다.

해당 부분을 root-context.xml에서 bean(객체)로 선언하는 코드를 작성합니다.



<beans> 태그 안에 해당 코드를 작성합니다.


property는 속성으로 해당 객체를 사용하기위한 속성들을 추가합니다.(.set 메소드라고 생각하면 됩니다.)


<bean id = "dataSource" class = "org.apache.commons.dbcp2.BasicDataSource" destroy-method="close"> 

 org.apache.commons.dbcp2.BasicDataSource의 객체를 생성한다. 객체명(id)는 dataSource로 한다.


<property> 는 .set 메소드 라고 생각하면 됩니다.


driverClassName(*){} 라고 BasicDataSource 클래스내에 정의 되어있을겁니다.

함수명 그대로 가져와서 사용하면 됩니다.


2번의 굵은 글씨로 적용되어있는 부분 중 .set 메소드 -> property로하여 속성 값을 넘겨줍니다.




4. root-context.xml에 설정된 dataSource를 이용하여 JUnit에서 테스트 해보기




src/test/java -> com.sora.shop.db -> ConnectionTest.java 를 생성합니다.(main 함수 없이 생성합니다.)




생성된 클래스에 어노테이션을 이용해 JUnit을 사용하는 클래스임을 명시해줍니다.

 @RunWith(SpringJUnit4ClassRunner.class)

 Runner클래스를 설정하면 JUnit에 내장된 Runner대신 그 클래스를 실행

 SpringJUnit4ClassRunner를 지정해줌

 @ContextConfiguration

("file:src/main/webapp/WEB-INF/spring/root-context.xml")

 root-context.xml 설정된 bean을 사용하기 위해 .xml 파일을 불러들인다.

 @Autowired

 root-context.xml 에 설정된 dataSource를 자동으로 주입해준다. 

 @Test

 public void 메소드가 테스트 케이스로 실행될 수 있음을 알린다.


그냥 이상태로 System.out.println()을 해서 잘 실행되는지 확인해도 된다.

(pom.xml -spring-test를 꼭 추가해줘야하며 JUnit 버전 4.12로 수정해야한다.)


connectionTest() 함수 내에


                Connection con = null;

PreparedStatement pstmt = null;

ResultSet rs = null;

try {

con = dataSource.getConnection();

pstmt = con.prepareStatement("select sysdate() from dual");

rs = pstmt.executeQuery();

while(rs.next())

System.out.println(rs.getString(1));

} catch (SQLException e) {

// TODO Auto-generated catch block

e.printStackTrace();

} finally {

// Close Statement and Connection

if (pstmt != null) {

try {

pstmt.close();

} catch (SQLException e) {

// TODO Auto-generated catch block

e.printStackTrace();

}

}

if (con != null) {

try {

con.close();

} catch (SQLException e) {

// TODO Auto-generated catch block

e.printStackTrace();

}

}


코드를 실행했을 경우



root-context.xml을 이용해서 DataSource 연동에 성공했음을 확인 할 수 있다^.^

'Study > Spring' 카테고리의 다른 글

[Spring] Mybatis 연동 (2)  (0) 2018.12.26
[Spring] Mybatis 연동 (1)  (0) 2018.12.24
[Spring] root-context.xml와 servlet-context.xml  (0) 2018.12.24
[Spring] Mysql과 JUnit (1)  (0) 2018.12.24
[Spring] pom.xml  (0) 2018.12.24
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
«   2024/05   »
1 2 3 4
5 6 7 8 9 10 11
12 13 14 15 16 17 18
19 20 21 22 23 24 25
26 27 28 29 30 31
글 보관함