이번장은 Spring3 + MyBatis 연동하여 DB에서 데이터 조회하는 테스트를 해보도록 하겠습니다.
MySQL JDBC를 이용하여 연동법을 설명하겠습니다.
Spring + Mybatis 연동을위한 pom.xml의 dependency를 등록해주세요
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 | < dependency > < groupId >org.mybatis</ groupId > < artifactId >mybatis</ artifactId > < version >3.2.7</ version > </ dependency > < dependency > < groupId >org.mybatis</ groupId > < artifactId >mybatis-spring</ artifactId > < version >1.2.2</ version > </ dependency > < dependency > < groupId >commons-dbcp</ groupId > < artifactId >commons-dbcp</ artifactId > < version >1.4</ version > </ dependency > < dependency > < groupId >org.springframework</ groupId > < artifactId >spring-jdbc</ artifactId > < version >${spring-framework.version}</ version > </ dependency > |
DBMS 별로 라이브러리 연동법은 하단을 참고해주세요.
2014/11/14 - [개발에필요한연동법/스프링연동] - Spring3 Maven을 이용하여 pom.xml에 oracle,mysql,mssql jdbc 라이브러리 등록하기
/resources/spring/application-config.xml 파일
beans태그사이에 다음과 같이 코드추가 해주세요
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | < context:component-scan base-package = "com.spring" /> < bean id = "dataSource" class = "org.apache.commons.dbcp.BasicDataSource" destroy-method = "close" > < property name = "driverClassName" value = "com.mysql.jdbc.Driver" /> < property name = "username" value = "DB계정" /> < property name = "password" value = "DB패스워드" /> </ bean > < bean id = "sqlSessionFactory" class = "org.mybatis.spring.SqlSessionFactoryBean" > < property name = "dataSource" ref = "dataSource" /> < property name = "mapperLocations" value = "classpath*:query/**" /> </ bean > < bean id = "sqlSession" class = "org.mybatis.spring.SqlSessionTemplate" > < constructor-arg ref = "sqlSessionFactory" /> </ bean > |
mapperLocations 속성값에 따라 다음과 같이 디렉토리를 생성해줍니다.
"/resources/query/"
디렉토리 생성이 완료되었으면
해당디렉토리에 "파일명.xml"을 생성하도록 합니다.
저는 임의로 "query.xml" 이라고 생성하였습니다.
다음코드를 붙여넣기 해주세요
1 2 3 4 5 6 7 | <? xml version = "1.0" encoding = "UTF-8" ?> <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd"> < mapper namespace = "query" > < select id = "test" resultType = "String" > SELECT 'test' </ select > </ mapper > |
이제는 DAO에대한 interface/class 파일을 생성해야하는데
저같은 경우는 패키지 + 파일을 하단처럼 생성하였습니다.
인터페이스는 생성하지 않고도 db연동은 가능하지만
대부분 생성하는 관계로 연결지어서 진행하겠습니다.
1 2 3 | public interface StudyDao { public void test() throws SQLException; } |
1 2 3 4 5 6 7 8 9 10 11 | @Repository public class StudyDaoImpl implements StudyDao { @Autowired private SqlSession query; @Override public void test() throws SQLException { query.selectOne( "query.test" ); } } |
위와 같이 선언해주시면 Spring + mybatis 연동은 끝난겁니다.
※ DAO 클래스에 @Repository 어노테이션을 필수로 작성해주셔야 합니다.
테스트를 위한 컨트롤러 코드를 작성해보도록 하겠습니다.
1 2 | @Autowired private StudyDao studyDao; |
StudyDao 인터페이스에 autowired 어노테이션을 선언합니다.
1 2 3 4 5 6 7 8 | @RequestMapping ( "/test" ) public void test(){ try { studyDao.test(); } catch (Exception e) { e.printStackTrace(); } } |
샘플 코드 작성이 완료 되었다면 한번 실행해보도록 하겠습니다.
상단 붉은색 네모친 부분이 이클립스의 콘솔부분입니다.
오류도 안나오고 어떠한 진행도 되지않아 동작이 되는지 확인이 되지 않습니다.
간단하게 DB로그를 출력해보고자 로그레벨을 변경해주도록 하겠습니다.
/resources/logback.xml 파일을 열어봅니다.
1 2 3 | < root level = "info" > < appender-ref ref = "console" /> </ root > |
위와같은 태그가 존재할텐데 level값을 보시면 "info" 라고 되어있습니다
"info" -> "debug"로 레벨 변경을 해주도록 합니다
저장 후 재실행을 컨트롤러를 재호출 해보도록 하겠습니다.
정상적으로 query.xml에 정의한 쿼리문이 호출되고
결과값까지 출력되는것을 확인하였습니다.
다음 포스팅은 트랜잭션 설정에 대하여 포스팅 해보도록 하겠습니다.
by 개발로짜
Spring3 + Mybatis 여러개 Datasource 연동법(다중 트랜잭션 포함) (0) | 2014.11.16 |
---|---|
Spring3 + Mybatis연동에 추가로 트랜잭션 설정 하여 실패시 Rollback 처리하기 (2) | 2014.11.14 |
Spring3 Maven을 이용하여 pom.xml에 oracle,mysql,mssql jdbc 라이브러리 등록하기 (0) | 2014.11.14 |
Spring3 인터셉터와 세션을이용하여 로그인 처리해보기 (2) | 2014.11.12 |
Spring3 RedirectAttributes 사용한 redirect POST 전송법 (0) | 2014.11.11 |