프로그래머스
Lombok
DTO(Data Transfer Object)
API
Rest
GET : 조회
@RequiredArgsConstructor
@RestController
public class CourseController {
private final CourseRepository courseRepository;
@GetMapping("/api/courses")
public List<Course> getCourses() {
return courseRepository.findAll();
}
}
POST : 생성
private final CourseService courseService;
// PostMapping을 통해서, 같은 주소라도 방식이 다름을 구분합니다.
@PostMapping("/api/courses")
public Course createCourse(@RequestBody CourseRequestDto requestDto) {
// requestDto 는, 생성 요청을 의미합니다.
// 강의 정보를 만들기 위해서는 강의 제목과 튜터 이름이 필요하잖아요?
// 그 정보를 가져오는 녀석입니다.
// 저장하는 것은 Dto가 아니라 Course이니, Dto의 정보를 course에 담아야 합니다.
// 잠시 뒤 새로운 생성자를 만듭니다.
Course course = new Course(requestDto);
// JPA를 이용하여 DB에 저장하고, 그 결과를 반환합니다.
return courseRepository.save(course);
}
public Course(CourseRequestDto requestDto) {
this.title = requestDto.getTitle();
this.tutor = requestDto.getTutor();
}
PUT
@PutMapping("/api/courses/{id}")
public Long updateCourse(@PathVariable Long id, @RequestBody CourseRequestDto requestDto) {
return courseService.update(id, requestDto);
}
// @PathVariable : {id}의 id가 Long id의 id라는 것을 나타내줌
// @RequestBody : Controller에서 요청을 받은 정보를 뒤에 requestDto 안에 넣어줌
// : POST, PUT은 API에서 넘어오는 데이터를 잘 받으려면 @RequestBody 형태로 받아줘야 함
DELETE
@DeleteMapping("/api/courses/{id}")
public Long deleteCourse(@PathVariable Long id) {
courseRepository.deleteById(id);
return id;
}
2주차 숙제
- 1주차 숙제로 작성한 Person 클래스를 CRUD할 수 있는 PersonController.java 파일을 만들고, 다음 API를 완성하세요.
- https://localhost:8080/api/persons POST : 친구 생성
- https://localhost:8080/api/persons GET : 친구 목록 조회
- https://localhost:8080/api/persons/{id} PUT : 친구 정보 변경
- https://localhost:8080/api/persons/{id} DELETE : 친구 정보 삭제
- ARC를 이용해 성공적으로 동작함을 확인하세요.
- 숙제 파일
- Person.java
- PersonRequestDto.java
- PersonRepository.java
- PersonService.java
- PersonController.java
@Getter
@NoArgsConstructor
@Entity
public class Person {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
@Column(nullable = false)
private String name;
@Column(nullable = false)
private int age;
@Column(nullable = false)
private String job;
@Column(nullable = false)
private String address;
public Person(PersonRequestDto requestDto) {
this.name = requestDto.getName();
this.age = requestDto.getAge();
this.job = requestDto.getJob();
this.address = requestDto.getAddress();
}
public void update(PersonRequestDto requestDto) {
this.name = requestDto.getName();
this.age = requestDto.getAge();
this.job = requestDto.getJob();
this.address = requestDto.getAddress();
}
}
public interface PersonRepository extends JpaRepository<Person, Long> {
}
@Setter
@Getter
@RequiredArgsConstructor
public class PersonRequestDto {
private final String name;
private final int age;
private final String job;
private final String address;
}
@RequiredArgsConstructor
@Service
public class PersonService {
private final PersonRepository personRepository;
@Transactional
public Long update(Long id, PersonRequestDto requestDto) {
Person person = personRepository.findById(id).orElseThrow(
() -> new IllegalArgumentException("해당 아이디가 존재하지 않습니다.")
);
person.update(requestDto);
return person.getId();
}
}
@RequiredArgsConstructor
@RestController
public class PersonController {
private final PersonRepository personRepository;
private final PersonService personService;
@GetMapping("/api/persons")
public List<Person> getPerson() {
return personRepository.findAll();
}
@PostMapping("/api/persons")
public Person createPerson(@RequestBody PersonRequestDto requestDto){
Person person = new Person(requestDto);
return personRepository.save(person);
}
@PutMapping("/api/persons/{id}")
public Long updatePerson(@PathVariable Long id, @RequestBody PersonRequestDto requestDto) {
return personService.update(id, requestDto);
}
@DeleteMapping("/api/persons/{id}")
public Long deletePerson(@PathVariable Long id) {
personRepository.deleteById(id);
return id;
}
}
과제도 해야하는데... 너무 어렵어요 저 LV1도 아직 제대로 못했는데 ㅠ 큰일났다