Restful API 서버에 MySql, MyBatis 활용한 데이터 관리

728x90

스프링 부트 프로젝트 생성

  • 프로젝트를 Web 서버에 올려야 하므로 ‘Spring Web’ 사용 설정 필수
  • MySql, MyBatis 활용한 DB 관리 위해 아래와 같이 사용설정 한다.

DB 연동 작업

  • MySql 안에 필요한 테이블 생성
  • 필요한 데이터 구조로 데이터 세팅
  • 프로젝트 내부 application.properties 프로퍼티 파일에 DB 연동 정보 작성

간단한 MVC 작업

  • Model : 데이터 관리
  • View : 보여주기
  • Controller : API 경로별 매핑 처리

>> DB 속 값을 GET 방식으로 RestAPI에 보내기

🟩 데이터 객체 생성

public class UserProfile { //DB 속 테이블 구조와 동일한 데이터 객체 
    private String id;
    private String name;
    private String phone;
    private String address;

    public UserProfile(String id, String name, String phone, String address) {
        super();
        this.id = id;
        this.name = name;
        this.phone = phone;
        this.address = address;
    }

    public String getId() {
        return id;
    }

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

    public String getName() {
        return name;
    }

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

    public String getPhone() {
        return phone;
    }

    public void setPhone(String phone) {
        this.phone = phone;
    }

    public String getAddress() {
        return address;
    }

    public void setAddress(String address) {
        this.address = address;
    }
}

🟩 MySql에 테이블 생성 후 사용할 데이터 삽입 처리

DB 속 테이블

🟩 Mapper 인터페이스 작성

  • MyBatis 라이브러리 활용하여 쉽게 SQL 매핑 가능 (@SELECT)
  • 단, DB 속에서 가져올 값에 #처리
@Mapper //매퍼 인터페이스 
public interface UserProfileMapper {  //MyBatis 활용하여 SQL 매퍼작업
    @Select("SELECT * FROM UserProfile WHERE id=#{id}")
    UserProfile getUserProfile(@Param("id") String id);

    @Select("SELECT * FROM UserProfile")
    List<UserProfile> getUserProfileList();

    @Insert("INSERT INTO UserProfile VALUES(#{id}, #{name}, #{phone}, #{address})")
    int insertUserProfile(@Param("id") String id, @Param("name") String name, @Param("phone") String phone, @Param("address") String address);

    @Update("UPDATE UserProfile SET name=#{name}, phone=#{phone}, address=#{address} WHERE id=#{id}")
    int updateUserProfile(@Param("id") String id, @Param("name") String name, @Param("phone") String phone, @Param("address") String address);

    @Delete("DELETE FROM UserProfile WHERE id=#{id}")
    int deleteUserProfile(@Param("id") String id);

}

🟩 컨트롤러 작성

package com.example.demo.controller;

import java.util.List;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.example.demo.mapper.UserProfileMapper;
import com.example.demo.model.UserProfile;

@RestController
public class UserProfileController {

    private UserProfileMapper mapper;

    public UserProfileController(UserProfileMapper mapper) {
        this.mapper = mapper;
    }

    @GetMapping("/user/{id}")
    public UserProfile getUserProfile(@PathVariable("id") String id) {
        return mapper.getUserProfile(id);
    }

    @GetMapping("/user/all")
    public List<UserProfile> getUserProfileList() {
        return mapper.getUserProfileList();
    }

    @PutMapping("/user/{id}")
    public void putUserProfile(@PathVariable("id") String id, @RequestParam("name") String name, @RequestParam("phone") String phone, @RequestParam("address") String address) {
        mapper.insertUserProfile(id, name, phone, address);
    }

    @PostMapping("/user/{id}")
    public void postUserProfile(@PathVariable("id") String id, @RequestParam("name") String name, @RequestParam("phone") String phone, @RequestParam("address") String address) {
        mapper.updateUserProfile(id, name, phone, address);
    }

    @DeleteMapping("/user/{id}")
    public void deleteUserProfile(@PathVariable("id") String id) {
        mapper.deleteUserProfile(id);
    }
}

🟦 실행시키기

  • 프로젝트 실행 시킨 뒤, 서버 위에 올라간 상태에서 localhost:8080/user/1 실행
  • DB 속 데이터가 출력되는 것을 확인할 수 있다.
  • [주의] 서버 중복되지 않게 종료 후 재실행해야 함(오류남)

🟦 PostMan 에서 해당 API GET 처리

        **- JSON 데이터 형태로 DB 속 값이 가져와지는 것 확인 가능** 

🟦 필요한 JSP 파일 생성

스프링부트는 앞서 말씀드린 것처럼 기본적으로 JSP를 지원하지 않습니다. 그래서 이전에 기본적으로 제공되었던 폴더들이 보이지 않습니다. 이전에 스프링을 하던 분들은 WEB-INF 폴더를 찾아 헤매셨겠지만, 스프링 부트에서는 해당 폴더가 자동으로 생성되지 않습니다. 그래서 결론적으로 JSP를 사용하기 위해 그리고 JSP 파일을 관리하기 위해서는 폴더를 직접 만들면 됩니다. 출처: https://gocoder.tistory.com/2438 [고코더 IT Express]
//사용자 요청 -> 응답(HTML 파일)
//@Controller

//사용자 요청 -> 응답(Data)
//@RestController

>> 요청한 값을 POST 방식으로 DB에 저장하기

🟩 MySql에 DB 테이블 생성

🟩 프로젝트 생성 후 데이터 객체 생성

🟩 DB 연동을 위한 프로퍼티 파일 생성

🟩 해당 데이터 Mapper 인터페이스 생성

@Mapper
public interface CompanyMapper {

    @Insert("INSERT INTO company(company_name, company_address) VALUES(#{company.name}, #{company.address})")
    @Options(useGeneratedKeys=true, keyProperty="id")
    int insert(@Param("company") Company company);

}

🟩 컨트롤러 작성

@RestController
@RequestMapping("/company")
public class CompanyController { //컨트롤러 

    @Autowired
    private CompanyMapper companyMapper;

    @PostMapping("")
    public int post(@RequestBody Company company) {
        return companyMapper.insert(company); 
        //입력 성공 시 1 반환 실패 시 0반환 
    }
}

🟦 실행

  • PostMan 에서 POST 방식으로 (”localhost:8080/company”) 넣고,
  • @RequstBody 로 받을 것이기 때문에 Body → JSON 형태로 데이터 보내기

DB 속에 값이 저장되어 있다.

728x90