Spring 서버에 MySQL DB 연결 및 API 리팩토링

728x90

🏓 Spring 서버에 MySQL DB 연결 및 API 리팩토링

  • 스프링 서버에 MySQL DB를 연결하고 기존 유저 저장 API와 조회 API를 리팩토링해보자.

🟦 1) 스프링 서버와 DB 연결

  • application.yml 파일 생성 후, 파일 내부에 서버와 연결할 DB 정보를 설정해야 한다.
spring:
	datasource:
		url: "jdbc:mysql://localhost/library"
		username : "root"
		password : "1234"
		driver-class-name: com.mysql.cj.jdbc.Driver
  • DB에 User 테이블을 생성해주자 (API가 사용할 테이터이므로)
create table users {//그냥 user는 인식 X
	id bigint auto_increment,
	name varchar(25),
	age int,
	primary key(id)
}
  • Controller 클래스 내부에서 생성자를 만들어주고, 생성자에 jdbcTemplete를 연결해준다.
//DB연결을 위해
    private final JdbcTemplate jdbcTemplate;
    //생성자로 연결
    public UserController(JdbcTemplate jdbcTemplate){

        this.jdbcTemplate = jdbcTemplate;//여기서 연결
    }

🟦 2) 기존 API 리팩토링

  • DB사용하도록 API 리팩토링을 한다.
  • POST API, GET API 변경
@RestController //진입점 등록
public class UserController {

    //DB연결을 위해
    private final JdbcTemplate jdbcTemplate;
    //생성자로 연결
    public UserController(JdbcTemplate jdbcTemplate){

        this.jdbcTemplate = jdbcTemplate;//여기서 연결
    }

    @PostMapping("/user") //리팫토링 시키기
    public void saveUser(@RequestBody UserCreateRequest request){
       //1) sql 문 작성
       String sql = "INSERT INTO person(name, age) VALUES(?,?)";
        //2) jdbvTemplate 에 보냄
        jdbcTemplate.update(sql, request.getName(), request.getAge());//?에 담길 데이터를 request에 접근하여 저장
    }

    @GetMapping("/user") //기존 사용자 목록 밖으로 응답할 용도 API
    public List<UserResponse> getUsers(){
        String sql = "SELECT * FROM person";
        return jdbcTemplate.query(sql, new RowMapper<UserResponse>(){
            @Override
            public UserResponse mapRow(ResultSet rs, int rowNum) throws SQLException {
                //쿼리 결과는 ResultSet 안에 모두 담겨 있다. rs로 접근하여 뷰로 보낼 데이터를 얻고, 반환용 객체에 세팅해주면 된다.
                long id = rs.getLong("id");
                String name = rs.getString("name");
                int age = rs.getInt("age");
                return new UserResponse(id, name, age); // 반환용 객체
            }
        });
    }
}

🏓 유저 업데이트 API, 삭제 API 개발 및 테스트

⬛ 유저 업데이트 API 개발 스펙

  • HTTP Method : PUT
  • HTTP path : /user
  • HTTP Body : (JSON)
  • 결과 반환 X

⬛ 유저 삭제 API 개발 스펙

  • HTTP Method : DELETE
  • HTTP path : /user
  • 쿼리 사용 → 삭제할 이름name 값 기준으로 삭제
  • 결과 반환 X
    @PutMapping("/user") //유저 어데이트 API
    public void updateUser(@RequestBody UserUpdateRequest request ){
        String sql = "UPDATE person SET name = ? WHRER id= ? ";
        jdbcTemplate.update(sql, request.getName(), request.getId());
    }

    @DeleteMapping("/user")
    public void deleteUser(@RequestParam String name){
        String sql = "DELETE FROM person WHERE name = ?";
        jdbcTemplate.update(sql, name);
    }

지금까지는 모든 기능이 대부분 Controller에 작성되어 있었다. 이 부분을 분리해야 한다. 추가로 구현해야할 요구사항이 많아지면 문제가 커진다.

첫 등록 화면
User 목록 도 정상적으로 불러와진다
DB에 잘 등록된 모습

728x90