Spring 실무 기초, 알고리즘

우정·2022년 12월 20일
0

[내일배움캠프] TIL

목록 보기
27/50

프로그래머스


Spring 실무 기초

Lombok

  • 자바 프로젝트를 진행할 때 필요한 메소드, 생성자 등을 자동 생성해줌으로써 코드를 절약할 수 있도록 도와주는 라이브러리

DTO(Data Transfer Object)

  • 데이터를 주고 받을 때 새로운 클래스를 만들어서 전달하자

API

  • 클라이언트 - 서버간의 약속
    클라이언트가 정한 대로 서버에게 요청(Request)을 보내면 서버가 요구사항을 처리해 응답(Response)을 반환함

Rest

  • 주소에 명사, 요청 방식에 동사를 사용함으로써 의도를 명확이 드러내는 것
  • 동사 : CRUD(POST, GET, PUT, DELETE)
  • 주의사항
    • 주소에 들어가는 명사들은 복수형을 사용
    • 주소에 동사는 가급적 사용 안함

  • GET : 조회

    • CourseController.java
    @RequiredArgsConstructor
    @RestController
    public class CourseController {
    
        private final CourseRepository courseRepository;
    
        @GetMapping("/api/courses")
        public List<Course> getCourses() {
            return courseRepository.findAll();
        }
    }
  • POST : 생성

    • CourseController.java
    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);
    }
    • Course 클래스 생성자 추가
    public Course(CourseRequestDto requestDto) {
      this.title = requestDto.getTitle();
      this.tutor = requestDto.getTutor();
    }
  • PUT

    • CourseController.java
    @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

    • CourseController.java
    @DeleteMapping("/api/courses/{id}")
    public Long deleteCourse(@PathVariable Long id) {
    		  courseRepository.deleteById(id);
    		  return id;
    }

2주차 숙제

@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();
    }
}
  • PersonRepository
public interface PersonRepository extends JpaRepository<Person, Long> {
}
  • PersonRequestDto
@Setter
@Getter
@RequiredArgsConstructor
public class PersonRequestDto {
    private final String name;
    private final int age;
    private final String job;
    private final String address;
}
  • PersonService
@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();
    }
}
  • PersonController
@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도 아직 제대로 못했는데 ㅠ 큰일났다

0개의 댓글

관련 채용 정보