스프링 프로젝트에 MariaDB 와 Mybatis를 연동 후 테스트 까지 해보겠습니다.
테스트 진행은 Maria DB의 테이블 및 테스트 칼럼이 샘플이 존재해야 합니다.
* 저는 testdb 테이블에 age 란 int형 칼럼이 존재 합니다.
첫 번째로, pom.xml 에 아래 dependency를 복사 및 붙여넣기 하세요.
*Mysql 과 Maria DB의 차이 ↓
http://gabrielyj.tistory.com/119?category=732269
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 | <!-- MariaDB --> <dependency> <groupid>org.mariadb.jdbc</groupid> <artifactid>mariadb-java-client</artifactid> <version>1.1.7</version> </dependency> <!-- Mybatis --> <dependency> <groupid>org.mybatis</groupid> <artifactid>mybatis</artifactid> <version>3.3.1</version> </dependency> <!-- Mybatis-Spring --> <dependency> <groupid>org.mybatis</groupid> <artifactid>mybatis-spring</artifactid> <version>1.2.4</version> </dependency> <!-- Mybatis Spring MVC --> <dependency> <groupid>org.springframework</groupid> <artifactid>spring-jdbc</artifactid> <version>${org.springframework-version}</version> </dependency> |
그 다음 WEB-INF폴더 -> spring폴더 -> root-context.xml 파일을 열어준뒤,
Namespace 메뉴를 클릭합니다.
(아래를 참고하고 aop, context, jdbc, mybatis-spring을 추가해주세요)
Namespaces에서 추가가 완료되면,
아래 내용을 root-context.xml 에 추가 해주세요.
url 의 jdbc:mysql:// 이후로는 사용하시는 IP와 포트 번호를 입력 해주시고,
username 과 password 는 각각 ID와 PW를 입력 해주시면 됩니다.
* 로컬 DB를 사용하시는분은 (jdbc:mysql://localhost:8080/DB이름) 을 입력 하시면 됩니다.
* 혹시 localhost 인데 포트번호가 8080 아니면 해당되는 포트번호를 꼭 입력 하셔야 합니다.
1 2 3 4 5 6 7 8 9 10 11 12 | <!-- 1. 데이터 베이스 연결 --> <bean id= "dataSource" class = "org.springframework.jdbc.datasource.DriverManagerDataSource" > <!-- <property name= "driverClassName" value= "org.mariadb.jdbc.Driver" /> --> <property name= "driverClassName" value= "com.mysql.jdbc.Driver" > <property name= "username" value= "해당DB의 ID" > <property name= "password" value= "해당DB의 PW" > </property></property></property></property></bean> <!-- 2. 순서대로 진행하기 위해 아래에 추가 하겠습니다. --> <!-- 3. 순서대로 진행하기 위해 아래에 추가 하겠습니다.--> |
그 다음 Java Resources 폴더-> src/main/resources 폴더 내부에
mappers 패키지 생성 후 그 안에 testMapper.xml 을 생성하고,
그 외부에 mybatis-config.xml 파일을 추가로 생성합니다.
testMapper.xml (DB 쿼리문을 작성하는 부분입니다.)
1 2 3 4 5 6 7 8 9 10 11 | <!--?xml version= "1.0" encoding= "UTF-8" ?--> <!-- 자바클래스에서 mapper 을 찾는 경로 다른 mapper와 중복되지 않도록 네임 스페이스 기재 --> <!--?xml version= "1.0" encoding= "UTF-8" ?--> <mapper namespace = "my.mappers.testMapper" > <select id= "selectTest" resulttype= "integer" > SELECT age FROM testdb </select> </mapper> |
mybatis-config.xml (이 부분은 테스트 하는 동안 수정할 필요 없습니다.입력만 잘해주세요.)
1 2 3 4 5 6 | <!--?xml version= "1.0" encoding= "UTF-8" ?--> <configuration> </configuration> |
그 다음 추가로 Java Resources 폴더-> src/main/resources 폴더 내부에
mybatisUtil 이란 패키지를 생성하고,
인터페이스 TService 와 클래스 TServiceImpl를 생성해줍니다.
이 부분은 컨트롤러와 mapper 사이를 연결해주는 부분입니다.
SqlSession을 Inject 해주고,
namespace 에는 *Mapper.xml 내에서 사용하는 이름과 똑같아야 합니다.
인터페이스 TService (in mybatisUtil package)
1 2 3 4 | package mybatisUtil; public interface TService { public int test(); } |
클래스 TServiceImpl (in mybatisUtil package)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 | <p>package mybatisUtil; import javax.inject.Inject; import org.apache.ibatis.session.SqlSession; import org.springframework.stereotype.Service; @Service public class TServiceImpl implements TService { @Inject private SqlSession sqlSession; private static final String namespace = "my.mappers.testMapper" ; @Override public int test() { return sqlSession.selectOne( namespace + ".selectTest" ); } } </p> |
이제 다시 root-context.xml 로 돌아가서 아까 입력 안한 2, 3번째 부분을 완성 합니다.
주의할 점은, mapperLocations 부분 부터
Mapper, Service, ServiceImpl 이 일치하지 않으면, 404에러 발생합니다.
404에러가 발생하면 꼭 *Mapper.xml 부터 절차적으로 확인 해보세요!
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | <!-- 2.SqlSessionFactory(파일 없으면 404에러뜸) --> <bean id= "sqlSessionFactory" class = "org.mybatis.spring.SqlSessionFactoryBean" > <property name= "dataSource" ref= "dataSource" ></property> <property name= "configLocation" value= "classpath:/mybatis-config.xml" ></property> <property name= "mapperLocations" value= "classpath:/mappers/*Mapper.xml" ></property> </bean> <!-- 3. SqlSessionTemplate DB연결 & 종료 --> <bean id= "sqlSession" class = "org.mybatis.spring.SqlSessionTemplate" destroy-method= "clearCache" > <constructor-arg name= "sqlSessionFactory" ref= "sqlSessionFactory" ></constructor-arg> </bean> <context:component-scan base-package= "Service위치 ex)mybatisUtil" ></context:component-scan> |
이렇게 DB연동 작업은 끝났습니다.
마지막으로 controller 에서 실행을 하면 됩니다.
Service 부분을 @Autowired 어노태이션을 입력 하여 TService 를 등록 해주시고,
ModelAndView형 메소드를 만들어 그 안에 test() 메소드를 실행 해줍니다.
*저는 바로 int 형으로 반환을 받고 뿌려주기 위해 int 형으로 선언 하였습니다.
그리고 addObject 메소드를 이용하여 mav 객체에 담아주고,
setViewName 메소드를 이용해 호출되는 페이지명도 담아줍니다.
* test.jsp 를 불러올것이기 때문에 test를 담았습니다.
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 | package controller; import javax.servlet.ServletException; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.servlet.ModelAndView; import mybatisUtil.TService; @Controller public class TestController { @Autowired private TService tDAO; @RequestMapping(value = "/test.do" ) public ModelAndView portList(ModelAndView mav) throws ServletException { int test = tDAO.test(); mav.addObject( "test" , test); mav.setViewName( "test" ); return mav; } } |
마지막으로 아래를 참고하여 test.jsp 를 생성해줍니다.
그 다음 EL문을 이용하여 ${test}를 입력 합니다
* 위에서 addObject 할 때 이름을 'test'로 했기 때문에 ${test}
그리고 !!!
http://localhost:8080/프로젝트명/test.do <- 접속하세요
이 부분이 말끔히 실행되려면, servlet-context.xml 부분의
preffix="/" suffix=".jsp" 입니다.
그래서 위에 setViewName 으로 넘어온 test가 /test.jsp 가 됩니다.
1 2 3 4 5 6 7 8 9 10 | <%@ page language= "java" contentType= "text/html; charset=UTF-8" pageEncoding= "UTF-8" %> <meta http-equiv= "Content-Type" content= "text/html; charset=UTF-8" > <title>Insert title here</title> ${test} |
최종 결과 : 저는 DB에 입력된 age 값이 '10' 이였습니다.