** mysql이 설치되어있다는 전제로 진행
1. pom.xml 파일에 dependency 추가
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 | <!-- MySQL --> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>6.0.6</version> </dependency> <!-- MyBatis --> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis</artifactId> <version>3.4.5</version> </dependency> <!-- MyBatis-Spring --> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis-spring</artifactId> <version>1.3.1</version> </dependency> <!-- Spring-jdbc --> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-jdbc</artifactId> <version>${org.springframework-version}</version> </dependency> | cs |
<version>에 ${org.springframework-version}라고 쓰여 있는 것은
pom.xml 상단에 설정된 프로퍼티를 따르겠다는 것
2. root-context.xml 수정
| <bean id="dataSources" class="org.springframework.jdbc.datasource.DriverManagerDataSource"> <property name="driverClassName" value="com.mysql.cj.jdbc.Driver"/> <property name="url" value="jdbc:mysql://localhost:3306/test_db?serverTimezone=UTC&useSSL=false"/> <property name="username" value="user01" /> <property name="password" value="1234" /> </bean> <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean"> <property name="dataSource" ref="dataSources" /> <property name="configLocation" value="classpath:mybatis/config/mybatis-config.xml" /> <property name="mapperLocations" value="classpath:mybatis/mapper/*.xml" /> </bean> <bean id="sqlSession" class="org.mybatis.spring.SqlSessionTemplate"> <constructor-arg name="sqlSessionFactory" ref="sqlSessionFactory" /> </bean> | cs |
beans 안에 위의 코드를 위치 시킨다. 몇몇 줄에 대한 설명을 첨부한다.
#1. 데이터베이스 구현체.. 프로퍼티로 데이터베이스 정보들을 넣어주어야 함
#3. 데이터베이스 url.. 기본적인 형식은 다음과 같다.
- jdbc:mysql://[ip]:[port]/[database]?serverTimezone=UTC
- ip에는 로컬에서 하기 위해 편하게 localhost를
- port는 mysql 설치시 변경하지 않았으면 3306이다.
- database는 테스트를 위해 test_db를 생성해두었다
#8. mybatis를 사용하기 위한 팩토리 생성
#10. mybatis 설정 파일의 경로를 지정해준다.
#11. mybatis맵퍼 파일들의 경로를 지정해준다
#14. spring-mybatis를 이용하면 세션관리를 알아서 잘 해준다. 이를 이용하기 위한 설정
3. mybatis xml 파일 생성
- root-context.xml 을 수정할 때 마이바티스 설정 파일들의 경로를 지정해줬었다. 없으면 에러가 날 것이므로 해당 파일들의 경로 및 파일을 생성해준다.
3-1. 경로 생성 및 파일 생성
- root-context.xml 수정할 때 [classpath:mybatis/mapper/*.xml]라는 값을 준 적이 있다. 해당 값은 다음의 의미를 가진다.
[classpath:] : src/main/resources 경로
[mybatis/mapper/*.xml] : mybatis/mapper/ 아래의 모든 xml파일
- 아래 첨부한 이미지와 같이 경로와 파일을 생성해준다.

3-2. xml 파일 생성
- mybatis-config.xml
- 마이바티스가 제공하는 여러 설정을 지정할 수 있는 파일이다.
| <?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config 3.0//EN" "http://mybatis.org/dtd/mybatis-3-config.dtd"> <configuration> </configuration> | cs |
- user-mapper.xml
- sql문을 입력할 파일이다.
| <?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="com.security.mysql.dao.UserDao"> </mapper> | cs |
#7. 맵퍼와 연결할 인터페이스. 혹은 클래스의 경로이다. 자신의 환경에 맞추어 설정하면된다. 본 설정에서는 인터페이스를 이용해 간단하게 이용해 볼 것이다.
4. 데이터베이스에 쿼리 날리기
- 스프링 프로젝트를 생성하면 기본적으로 설정되는 파일 내에서 테스트를 해볼 것이다.
- 쿼리 작성을 위해 데이터베이스에 미리 간단한 테이블을 생성해두었다.
- 내용은 아무것도 넣지 않은 상태이다.
| CREATE TABLE `user` ( `idx` INT(11) NOT NULL AUTO_INCREMENT, `user_id` VARCHAR(50) NOT NULL, `user_pwd` VARCHAR(50) NOT NULL, PRIMARY KEY (`idx`) ) ENGINE=InnoDB ; | cs |
- 3번에서 파일 생성을 완료 했다면 디렉토리 구조는 아래와 같을 것이다.

4-1. 쿼리 작성
- 위에서 생성한 user 테이블에 입력된 데이터 수를 가져오는 쿼리를 만들어 볼 것이다.
- 쿼리 작성은 인터페이스와 맵퍼 두 파일 모두에서 할 수 있다.
- 맵퍼 파일을 이용할 경우 여러 옵션 추가나 if문 등도 사용할 수 있다.
- 인터페이스에서 작성하는 방법은 아래와 같다
| public interface UserDao { @Select("select count(*) from user") int getUserCnt(); } | cs |
#3. 어노테이션을 이용해 쿼리를 인터페이스에서 바로 작성한다.
#4. 해당 쿼리를 호출할 메소드명
- 맵퍼를 이용하는 방법은 인터페이스, 맵퍼파일을 모두 수정해야 한다.
- UserDao.java
| public interface UserDao { int getUserCnt(); } | cs |
#3. 맵퍼파일의 id를 메소드 이름 설정하고 resultType를 반환값으로 설정
- user-mapper.xml
| <mapper namespace="com.security.mysql.dao.UserDao"> <select id="getUserCnt" resultType="int"> select count(*) from user </select> </mapper> | cs |
#3. getUserCnt라는 이름의 select문이고 반환타입은 int이다.
#5. 쿼리
4-2. 쿼리 호출
- 4-1에서 작성한 쿼리를 호출해 볼 것이다. 작성방법 두 가지 중에 어떤 것을 사용했더라도 호출 방법은 동일하다. 프로젝트 생성시 기본적으로 만들어지는 HomeController.java 파일에 코드를 추가해 볼 것이다.
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 | @Controller public class HomeController { private static final Logger logger = LoggerFactory.getLogger(HomeController.class); @Autowired private SqlSession SqlSession; @RequestMapping(value = "/", method = RequestMethod.GET) public String home(Locale locale, Model model) { logger.info("Welcome home! The client locale is {}.", locale); Date date = new Date(); DateFormat dateFormat = DateFormat.getDateTimeInstance(DateFormat.LONG, DateFormat.LONG, locale); String formattedDate = dateFormat.format(date); UserDao userDao = SqlSession.getMapper(UserDao.class); int userCnt = userDao.getUserCnt(); System.out.println("userCnt : " + userCnt); model.addAttribute("serverTime", formattedDate );
return "home"; } } | cs |
- HomeController.java 생성시에 없던 코드는 굵게 표시해두었다.
#6~7. root-context.xml에 생성해둔 sqlSession을 이용하기 위함
#18~20. 쿼리 실행한 값을 userCnt에 담고, 받아온 값을 확인하기 위함
여기까지 작성한 후 서버를 실행하고 기본 페이지로 접속을 하면 아래와 같은 내용이 sts 콘솔에 찍힐 것이다.

본 글은 간단하게 세팅하는 방법만 기록해두었다.
여러 옵션을 사용하는 방법에 대한 공부가 필요하다..