STUDY/Spring
REST API 실습
seonyounggg
2021. 1. 26. 23:50
Person테이블에 데이터를 CRUD하는 API를 작성하였다.
Person.java
@Setter
@Getter
@NoArgsConstructor
@Entity
public class Person extends Timestamped {
@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;
public Person(String name, int age, String job) {
this.name = name;
this.age = age;
this.job = job;
}
public Person(PersonRequestDto requestDto){
this.name=requestDto.getName();
this.age=requestDto.getAge();
this.job=requestDto.getJob();
}
public void update(PersonRequestDto requestDto) {
this.name=requestDto.getName();
this.age=requestDto.getAge();
this.job=requestDto.getJob();
}
}
PersonRequestDto.java
@Getter
@Setter
@RequiredArgsConstructor
public class PersonRequestDto {
private String name;
private int age;
private String job;
}
PersonRepository.java
public interface PersonRepository extends JpaRepository<Person, Long> {
}
PersonService.java
@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("id not exists")
);
person.update(requestDto);
return person.getId();
}
}
PersonController.java
@RequiredArgsConstructor
@RestController
public class PersonController {
private final PersonRepository personRepository;
private final PersonService personService;
//GET API
@GetMapping("/api/persons")
public List<Person> getPersons(){
return personRepository.findAll();
}
//POST API
@PostMapping("/api/persons")
public Person createPerson(@RequestBody PersonRequestDto requestDto){
Person person = new Person(requestDto);
return personRepository.save(person);
}
//PUT API
@PutMapping("/api/persons/{id}")
public Long updatePerson(@PathVariable Long id, @RequestBody PersonRequestDto requestDto){
return personService.update(id, requestDto);
}
//DELETE API
@DeleteMapping("/api/persons/{id}")
public Long deletePerson(@PathVariable Long id){
personRepository.deleteById(id);
return id;
}
}