본문 바로가기

BackEnd : Spring/SpringBoot

Spring Boot Server & Android Client App - Chapter #3

@GetMapping : for making a get request api endpoint

1. Create new Rest Controller class

EmployeeController

package com.genuinecoder.springserver.controller;

import com.genuinecoder.springserver.model.employee.Employee;
import com.genuinecoder.springserver.model.employee.EmployeeDao;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

@RestController
public class EmployeeController {

    @Autowired
    private EmployeeDao employeeDao;
    @GetMapping("/employee/get-all")
    public List<Employee> getAllEmployees() {
        return employeeDao.getAllEmployees();
    }
}

2. Create GET Endpoint

EmployeeController.java

package com.genuinecoder.springserver.controller;

import com.genuinecoder.springserver.model.employee.Employee;
import com.genuinecoder.springserver.model.employee.EmployeeDao;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

@RestController
public class EmployeeController {

    @Autowired
    private EmployeeDao employeeDao;
    @GetMapping("/employee/get-all")
    public List<Employee> getAllEmployees() {
        return employeeDao.getAllEmployees();
    }
}

3. Test GET Endpoint with postman

 

4. CREATE POST endpoint

EmployeeController

@PostMapping("/employee/save")
    public void save(@RequestBody Employee employee) {
        employeeDao.save(employee);
    }

database에 저장되어있던 정보들 지우기

5. Test POST Endpoint with postman

employee를 JSON 형태로 보내야함

mysql에서 성공적으로 보내진거 확인 가능

6. Improve POST endpoint by returning Employee object

선생님이 하신 말

when we save something we save it and return the same object this is important because when we are giving trying to save something we are not giving the id it is auto generated so if we want to later use that auto generated value we have to use the return object

-> id가 auto generated되니까 나중에 이 객체를 쓰려면 id를 return해서 확인해야 한다는 ?? 느낌으로 난 이해했다

그래서 post할때마다 저장된 객체가 리턴되게 짜야 한다고 하셨음

EmployeeDao에서 

public Employee save(Employee employee) {
        return repository.save(employee);
    }

로 수정, 저장된 Employee 객체를 바로 리턴하게 함

EmployeeController

@PostMapping("/employee/save")
    public Employee save(@RequestBody Employee employee) {
        return employeeDao.save(employee);
    }