코코딩딩

[스프링/springboot] restapi 만들기 (mybatis, postgresql) 본문

일단기록/매일기록

[스프링/springboot] restapi 만들기 (mybatis, postgresql)

겟츄 2022. 5. 13. 16:40

예전에 스프링 프레임워크로 만들었던 restapi를 springboot로 구현하고자 한다.

 

결과적으로 봤을 때 boot가 설정할 부분이 더 적기 때문에 더 간편하게 구현할 수 있다.

 

spring-boot, mybatis, postgresql

 

 


 

 

프로젝트 생성하기

 

 

spring starter project 를 이용해 maven 프로젝트를 만들어준다. 

사용할 dependency는 다음과 같다.

 

1. spring boot devtools

2. spring web

3. jdbc api

4. myBatis framework

5. postgresql driver

 

 

mapper,service등의 패키지를 만들때 경로는 기본 application 파일이 있는 위치를 신경써주어야 한다.

예를들어 com.example.apiex 패키지에 RestApiExampleApplication.java가 있을경우

service 파일이 들어갈 패키지명은 com.example.apiex.service로 해주어야 경로 오류가 나지 않는다.

 

 

 

 * 프로젝트 구조

 

 

application.properties 설정

 

 

## DB setting
spring.datasource.driver-class-name=org.postgresql.Driver
spring.datasource.url=jdbc:postgresql://DBurl
spring.datasource.username=아이디
spring.datasource.password=비밀번호

 

DB에 접속하기 위한 정보들을 입력해준다.

 

 

DatabaseConfig.Class 만들기

 

 

import javax.sql.DataSource;

import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.SqlSessionTemplate;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.transaction.annotation.EnableTransactionManagement;

@Configuration
@MapperScan(basePackages = "com.example.apiex.mapper")
@EnableTransactionManagement
public class DatabaseConfig {

    @Bean
    public SqlSessionFactory sqlSessionFactory(DataSource dataSource) throws Exception {
        final SqlSessionFactoryBean sessionFactory = new SqlSessionFactoryBean();
        sessionFactory.setDataSource(dataSource);
        PathMatchingResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
        sessionFactory.setMapperLocations(resolver.getResources("mapper/*.xml"));
        return sessionFactory.getObject();
    }

    @Bean
    public SqlSessionTemplate sqlSessionTemplate(SqlSessionFactory sqlSessionFactory) throws Exception {
        final SqlSessionTemplate sqlSessionTemplate = new SqlSessionTemplate(sqlSessionFactory);
        return sqlSessionTemplate;
    }
}

 

bean에 필요한 것들을 등록해준다.

 

 

mapper.xml 만들기

 

resources에 mapper 폴더를 만들고 mapper.xml 파일을 만들어주고 원하는 sql문을 작성해준다.

 

기존에 있던 db를 사용할 예정이라 user_info에 있는 데이터 중 id와 생년월일을 10개 select할 예정이다.

 

<?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.example.apiex.mapper.ApiMapper">

    <select id="SelectUser" resultType="com.example.apiex.model.UserVO">
		select user_id , user_br_ymd from user_info limit 10
    </select>

</mapper>

 

Vo 만들기

 

user의 id와 생일을 담을 VO 객체 생성

 

package com.example.apiex.model;

public class UserVO {
	private String user_id;
	private String user_br_ymd;
	
	public String getUser_id() {
		return user_id;
	}
	public void setUser_id(String user_id) {
		this.user_id = user_id;
	}
	public String getUser_br_ymd() {
		return user_br_ymd;
	}
	public void setUser_br_ymd(String user_br_ymd) {
		this.user_br_ymd = user_br_ymd;
	}
	
	
}

 

 

mapper.class 만들기

 

xml로 만든 mapper를 사용하기 위한 interface 선언 mapper에 있는 id와 이름이 같게 설정한다.

 

package com.example.apiex.mapper;

import java.util.List;

import com.example.apiex.model.UserVO;

public interface ApiMapper {
	public List<UserVO> SelectUser() throws Exception;
	
}

 

 

service 만들기

 

service는 interface와 상속받은 Impl 두개를 만들어준다.

 

package com.example.apiex.service;

import java.util.List;

import com.example.apiex.model.UserVO;

public interface ApiService {
	public List<UserVO> SelectUser() throws Exception;
}

 

 

package com.example.apiex.service;

import java.util.List;

import org.apache.ibatis.session.SqlSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.example.apiex.mapper.ApiMapper;
import com.example.apiex.model.UserVO;

@Service
public class ApiServiceImpl implements ApiService {
	
	@Autowired
	private SqlSession sqlSession;
	
	@Override
	public List<UserVO> SelectUser() throws Exception {
		ApiMapper mappers = sqlSession.getMapper(ApiMapper.class);
		List<UserVO> vos = mappers.SelectUser();
		return vos;
	}

}

 

 

restController 만들기

 

 

package com.example.apiex.controller;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import com.example.apiex.model.UserVO;
import com.example.apiex.service.ApiService;


@RestController
@RequestMapping(value="/rest")
public class ApiRestController {

	@Autowired
	ApiService service;
	
	@ResponseBody
	@PostMapping("selectraw")
	public ResponseEntity<?> selectRaw() throws Exception {
		
	
		List<UserVO> result = service.SelectUser();
		
		
		return ResponseEntity.ok(result);
	}
}

 

@PostMapping 을 @GetMapping 으로 만들어주면 get방식으로 요청할 수 있는 restapi를 만들 수 있다.

 

postman을 이용해 요청을 보내면 다음과 같은 내용응 응답받을 수 있다. (db에 10개 select한 결과물)

 

[
    {
        "user_id": "nUser1",
        "user_br_ymd": "20211203"
    },
    {
        "user_id": "nUser11",
        "user_br_ymd": "20211201"
    },
    {
        "user_id": "nUser12",
        "user_br_ymd": "20211211"
    },
    {
        "user_id": "nUser13",
        "user_br_ymd": "20211212"
    },
    {
        "user_id": "nUser2",
        "user_br_ymd": "20211204"
    },
    {
        "user_id": "nUser3",
        "user_br_ymd": "20211205"
    },
    {
        "user_id": "test0",
        "user_br_ymd": "19510101"
    },
    {
        "user_id": "test11",
        "user_br_ymd": "19440101"
    },
    {
        "user_id": "test9",
        "user_br_ymd": "19560101"
    },
    {
        "user_id": "test26",
        "user_br_ymd": "19370201"
    }
]