Woopii Vyeolog

[Spring Boot] Mybatis Sample 본문

Spring Boot

[Spring Boot] Mybatis Sample

WooPii 2022. 2. 5. 14:49

● 참고 문서

https://mybatis.org/spring/ko/index.html

 

mybatis-spring –

소개 MyBatis-Spring 은 무엇일까? 마이바티스 스프링 연동모듈은 마이바티스와 스프링을 편하고 간단하게 연동한다. 이 모듈은 마이바티스로 하여금 스프링 트랜잭션에 쉽게 연동되도록 처리한다.

mybatis.org

 

 

● Mybatis 관련 라이브러리 의존성 추가

pom.xml 에 dependency 추가

<dependency>
    <groupId>org.mybatis</groupId>
    <artifactId>mybatis</artifactId>
    <version>3.5.7</version>
</dependency>
<dependency>
    <groupId>org.mybatis</groupId>
    <artifactId>mybatis-spring</artifactId>
    <version>2.0.7</version>
</dependency>

 

 

● Controller, Service, Mapper, Vo 파일 생성

## 디렉토리 구조

1. vo 생성

package com.project.clone_louisquatorze.sample.mybatis.vo;

public class SampleMybatisVo {
    
    private Long id;
    private String name;


    // Getter, Setter
    public Long getId() {
        return this.id;
    }

    public void setId(Long id) {
        this.id = id;
    }

    public String getName() {
        return this.name;
    }

    public void setName(String name) {
        this.name = name;
    }

    //ToString
    @Override
    public String toString() {
        return "{" +
            " id='" + getId() + "'" +
            ", name='" + getName() + "'" +
            "}";
    }

}

 

2. java Mapper 생성

## @Mapper 어노테이션은 해당 클래스가 Mybatis Mapper임을 알려주는 어노테이션이다.

후에 작성할 base packeges 설정에서 package경로가 설정되어 있다면 생략이 가능하다.

package com.project.clone_louisquatorze.sample.mybatis.mapper;

import java.util.List;

import com.project.clone_louisquatorze.sample.mybatis.vo.SampleMybatisVo;

import org.apache.ibatis.annotations.Mapper;

//import org.apache.ibatis.annotations.Mapper;

@Mapper       //Mybatis Mapper임을 명시 하는 어노테이션
public interface SampleMybatisMapper {

    //전체 리스트 조회
    public List<SampleMybatisVo> list();
    
}

 

3. service, serviceImpl 생성

## service

package com.project.clone_louisquatorze.sample.mybatis.service;

import java.util.List;

import com.project.clone_louisquatorze.sample.mybatis.vo.SampleMybatisVo;

public interface SampleMybatisService {
    
    // 전체 리스트 조회
    List<SampleMybatisVo> list();
    
}

 

## serviceImpl

package com.project.clone_louisquatorze.sample.mybatis.service.Implement;

import java.util.List;

import com.project.clone_louisquatorze.sample.mybatis.mapper.SampleMybatisMapper;
import com.project.clone_louisquatorze.sample.mybatis.service.SampleMybatisService;
import com.project.clone_louisquatorze.sample.mybatis.vo.SampleMybatisVo;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service    //서비스 임을 명시
public class SmapleMybatisSeriveImpl implements SampleMybatisService {
    
    @Autowired
    private SampleMybatisMapper sampleMybatisMapper;

    /**
     * 전체 리스트 조회
     */
    @Override
    public List<SampleMybatisVo> list() {
        return sampleMybatisMapper.list();
    }

}

 

 

4. Controller 생성

package com.project.clone_louisquatorze.sample.mybatis.controller;

import com.project.clone_louisquatorze.sample.mybatis.service.SampleMybatisService;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;

@Controller     //Contoller임을 명시
@RequestMapping(value = "/api/sample/mybatis")      //Url Prefix를 명시
public class SampleMybatisController {

    @Autowired
    private SampleMybatisService sampleMybatisService;
    
    /**
     * 전체 리스트 조회
     * @return  전체 리스트
     */
    @GetMapping(value = "/list")
    public ResponseEntity<?> list() {
        return ResponseEntity.ok().body(sampleMybatisService.list());
    }

}

 

● Mybatis 설정파일 생성

1. Mybatis Mapper 설정

## @Configuration : 설정파일임을 나타내는 어노테이션 + 해당 클래스 안에서 Bean을 등록하면 해당 Bean 들은 스프링 컨테이너에서 관리하게 되고, 싱글톤을 유지하게 된다.

## MapperScan안의

basePackage :  Mapper를 찾을 Package를 명시하는 속성이다.

annotationClass : @Mapper 어노테이션을 적용하기 위한 속성 basePackage안에 @Mapper 어노테이션 붙은 클래스만 mybatis Mapper로 인식한다.

sqlSessionFactoryRef : sqlSessionFactory로 등록할 Bean을 명시

 

## sqlSession : 실제 sql을 전송하는 역활을 가진 세션

## sqlSessionFactory : sqlSession을 관리하는 역활, DB 연결정보인 DataSource 메타 정보를 가지고 있어야 한다. 설정파일에서 Bean으로 등록한다.

 

package com.project.clone_louisquatorze.config;

import javax.sql.DataSource;

import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;

@Configuration      //설정파일임을 나타내는 어노테이션 , @Bean 등록을 위한 어노테이션(스프링 컨테이너에서 관리 되며 Bean들이 싱글톤을 유지하게 한다)
@MapperScan(        //Mybatis Mapper를 설정하기 위한 어노테이션
    basePackages = {"com.project.clone_louisquatorze.sample.mybatis.mapper"},   //Mapper를 찾을 Package를 명시하는 속성
    annotationClass = org.apache.ibatis.annotations.Mapper.class,               //@Mapper 어노테이션을 적용하기 위한 속성 basePackage안에 @Mapper 어노테이션 붙은 클래스만 mybatis Mapper로 인식 
    sqlSessionFactoryRef = "sqlSessionFactory")                                 //sqlSessionFactory이름으로 등록된 Bean을 찾아 sqlSessionFactory로 사용
public class MybatisConfig {

    @Bean(name = "sqlSessionFactory")   //sqlSessionFactory라는 이름으로 Bean등록
    public SqlSessionFactory sqlSessionFactory(@Qualifier("dataSource") DataSource dataSource) throws Exception {

        SqlSessionFactoryBean sqlSessionFactoryBean = new SqlSessionFactoryBean();      //Bean으로 등록할 SqlSessionFactory객체 생성
        sqlSessionFactoryBean.setDataSource(dataSource);        //sqlSessionFactoryBean에 dataSource정보를 set함 (Datasource정보는 application.yml에 명시함)
        sqlSessionFactoryBean.setMapperLocations(new PathMatchingResourcePatternResolver().getResources("classpath:/mybatis/*/mapper/*Mapper.xml"));    //Mapper xml파일의 위치를 명시
        return sqlSessionFactoryBean.getObject();

    }

}

 

 

● Mapper 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.project.clone_louisquatorze.sample.mybatis.mapper.SampleMybatisMapper">

    <select id="list" resultType="com.project.clone_louisquatorze.sample.mybatis.vo.SampleMybatisVo">
        SELECT * FROM tb_sample
    </select>

</mapper>

 

 

● Database 상태

 

 

● Controller 호출 결과

 

 

Comments