Web Programming

Spring Boot에서 MyBatis 적용

안녕하세요, 씨앤텍시스템즈 육지후 연구원입니다.

 

이번 포스트에서는 SpringBoot에서 MyBatis를 적용하는 방법에 대해 작성하려 합니다.

 

※  사전에 Spring Boot가 설치되어 있어야 합니다. ※

※  해당 포스트는 Oracle을 사용하지만 다른 DB도 사용할 수 있습니다. ※

MyBatis Logo


1. MyBatis란?

 MyBatis는 간단하게 데이터베이스를 쉽게 다룰 수 있도록 도와주는 프레임워크입니다. 프로그램에 있는 SQL 쿼리들을 한 구성파일에 구성하여 프로그램 코드와 SQL을 분리할 수 있는 장점을 가지고 있고 조회 결과를 사용자 정의 DTO, MAP 등으로 맵핑하여 사용할 수 있어 빠른 개발이 가능하고 생산성이 향상된다는 특징이 있습니다.

 

2.  환경설정

pom.xml

<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>3.0.0</version>
</dependency>

 Spring Boot 프로젝트 생성 시 Spring Boot Starter에 MyBatis Framework 혹은 아래 코드를 pom.xml에 추가합니다.


application.properties

spring.datasource.url=jdbc:oracle:thin:@localhost:1521/cdb1?characterEncoding=UTF-8&serverTimezone=UTC
spring.datasource.username={DB 아이디}
spring.datasource.password={DB 비밀번호}

 DB와 연결해줍니다.

 

SpringBootApplication

@Bean
	public SqlSessionFactory sqlSessionFactory(DataSource dataSource) throws Exception{
		SqlSessionFactoryBean sessionFactory = new SqlSessionFactoryBean();
		sessionFactory.setDataSource(dataSource);
		
        /* xml 파일 위치 지정 */
        /* src/main/resources에 있는 mapper폴더 아래 모든 xml 파일 */
        Resource[] res = new PathMatchingResourcePatternResolver().getResources("classpath:mapper/*.xml");
        sessionFactory.setMapperLocations(res);
        
        /* xml 파일에서 사용할 Model 폴더 지정 */
        sessionFactory.setTypeAliasesPackage("com.cnt.hmm.cognos.portal.model");
		
        return sessionFactory.getObject();
}

3. 로직 작성

Model

public class User {

	private String userId;
	private String userNm;
	private String userPw;
	private String userEmail;
	private String userPh;
	private String userLocation;
	private int userFailCount;
    		
            		⋮
    }

 

 

Controller

@RestController
public class UserController {

	/* 의존성 주입 */
    @Autowired
    public UserController(UserService userService) {
        this.userService = userService;
    }
	
    /* 유저 정보 불러오기 */
    @GetMapping(value = "/api/cnt/test")
    public HashMap<Object, Object> test() throws Exception {
        HashMap<Object, Object> result = new HashMap<Object, Object>();
        try {
            List<User> userList = userService.selectUserList();
            result.put("result", userList);
        } catch(Exception e) {
            e.printStackTrace();
        }
        return result;
    }
 }

 

Service

public interface UserService {

    List<User> selectUserList() throws Exception;
}

 

ServiceImpl

@Service
public class UserServiceImpl implements UserService {

    private UserMapper userMapper;

    @Autowired
    public UserServiceImpl(UserMapper userMapper) {
        this.userMapper = userMapper;
    }

    @Override
    public List<User> selectUserList() throws Exception {
        return userMapper.selectUserList();
    }
}

 

Mapper

@Mapper
public interface UserMapper {

    List<User> selectUserList() throws Exception;
}

 

xml

<?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.cnt.hmm.cognos.portal.mapper.UserMapper">

    <select id="selectUserList" resultType="User">
        SELECT USER_ID as userId
             , USER_NM as userNm
             , USER_PW as userPw
             , USER_EMAIL as userEmail
             , USER_PH as userPh
             , USER_LOCATION as userLocation
             , USER_FAIL_COUNT as userFailCount 
          FROM USER_INFO_VIEW ORDER BY USER_ID DESC
    </select>
	
</mapper>

 

 위에서 Model 클래스의 경로를 설정했기 때문에 resultType에 클래스명으로만 작성이 가능합니다.

 데이터를 가져올 때 저장할 객체의 속성 이름과 같도록 as를 사용해서 데이터를 객체로 받습니다.

 객체와 이름을 동일하게 적을 경우 객체로 정보가 알아서 저장됩니다.


 3. 결과

 로직을 작성했으니 Postman으로 테스트를 해보겠습니다.

 

Postman Request


 

 요청을 보내게 되면 사진과 같이 결과가 나오게 됩니다.

 

Oracle Data (DBeaver)

 그리고 DB에 있는 Data를 확인해보면 일치하여 결과가 잘 나온다는 것을 확인할 수 있습니다.


지금까지 SpringBoot에서 MyBatis를 적용하고 사용하는 방법에 대해 작성해보았습니다.

감사합니다.

 

 

728x90