Notice
Recent Posts
Recent Comments
관리 메뉴

Developer Gonie

스프링 부트 (Spring Boot) 에서 MyBatis 적용하기 본문

개인 공부/Spring Boot

스프링 부트 (Spring Boot) 에서 MyBatis 적용하기

이대곤 2023. 2. 24. 11:58

1. build.gradle 에 아래 dependency 추가하기

// MyBatis 
implementation group: 'com.oracle.database.jdbc', name: 'ojdbc11', version: '21.8.0.0'
implementation 'org.mybatis.spring.boot:mybatis-spring-boot-starter:3.0.0'

2. application.properties 에 아래 내용 추가하기

#Oracle DataSource
spring.datasource.driver-class-name=oracle.jdbc.driver.OracleDriver
spring.datasource.url=jdbc:oracle:thin:@127.0.0.1:1521/orcl
spring.datasource.username=temp
spring.datasource.password=1234

# Mapper Xml Location
mybatis.mapper-locations=classpath:mappers/*.xml

3. Mapper 인터페이스 생성하기

package com.example.demo.repository;

import org.apache.ibatis.annotations.Mapper;
import com.example.demo.entity.Fruit;

@Mapper
public interface FruitMapper {
    Fruit selectById(String no);
}

4. src/main/resources 아래에 mappers 폴더 추가 후 xml 생성하기

* namespace는 인터페이스로 맞춰주면 된다.
* mappers 폴더는 application.properties 에 이렇게 명시해줬기 때문에 그런거지 내 입맛대로 수정 가능

<?xml version="1.0" encoding="UTF-8" ?>

<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTO Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">

<mapper namespace="com.example.demo.repository.FruitMapper">
    <select id="selectById" resultType="com.example.demo.entity.Fruit">
        SELECT * FROM tbl_fruit WHERE no = #{no}
    </select>
</mapper>

5. Mapper 인터페이스를 사용하여 결과를 반환하는 서비스 생성

package com.example.demo.service;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import com.example.demo.entity.Fruit;
import com.example.demo.repository.FruitMapper;

@Service
public class MyService {
	
	@Autowired
	FruitMapper fruitMapper;
	
	public Fruit getFruit(String no) {
		return fruitMapper.selectById(no);
	}
}

6. Mapper 인터페이스를 사용하여 결과를 반환하는 서비스 생성

package com.example.demo.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;
import com.example.demo.entity.Fruit;
import com.example.demo.service.MyService;

@RestController
public class MyController {
	
	@Autowired
	MyService myservice;
	
	@GetMapping("/fruit/{no}")
	public Fruit asda(@PathVariable String no) {
		return myservice.getFruit(no);
	}
}
Comments