Person 클래스를 만들고, 멤버변수(id,name,job) private 으로 설정.
@Entity 로 테이블 생성해주고
@Getter 로 멤버변수 사용할수 있게 해주고,
@NoArgsConstructor 로 기본생성자 설정.
@GeneratedValue(strategy = GenerationType.AUTO) 로 자동증가
@Id 로 id 값 설정
각 멤버변수마다 @Column(nullable = false) 으로 꼭 있어야 하는 테이블 열 생성
Person 기본메소드, 정보 받아오고
update 로 수정정보 받아온다.
@Getter
@NoArgsConstructor
@Entity
public class Person {
@GeneratedValue(strategy = GenerationType.AUTO)
@Id
private Long id;
@Column(nullable = false)
private String name;
@Column(nullable = false)
private String job;
@Column(nullable = false)
private int age;
@Column(nullable = false)
private String address;
public Person(PersonRequestDto requestDto) {
this.name = requestDto.getName();
this.job = requestDto.getJob();
this.age = requestDto.getAge();
this.address = requestDto.getAddress();
}
public void update(PersonRequestDto requestDto) {
this.name = requestDto.getName();
this.job = requestDto.getJob();
this.age = requestDto.getAge();
this.address = requestDto.getAddress();
}
}
@Getter
public class PersonRequestDto {
private String name;
private String job;
private int age;
private String address;
}
public interface PersonRepository extends JpaRepository<Person, Long> {
}
@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가 존재하지 않습니다.")
);
person.update(requestDto);
return person.getId();
}
}
@RequiredArgsConstructor
@RestController
public class PersonController {
private final PersonService personService;
private final PersonRepository personRepository;
@GetMapping("/api/persons")
public List<Person> getPersons() {
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;
}
}
[Application.java]