ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • 스프링 부트 (메모장만들기) *
    스프링 2023. 4. 17. 19:21
    Method URL Request Response
    POST /api/memos
    {
        "username" : "name",
        "contents" : "contents",
        "password" : 123
    }
    {
        "username""name",
        "contents""contents",
        "id" : 1 
        "password"123,
        "modifiedAt""createAt"
    }
    GET /api/memos   all data
    {
        "username""name",
        "contents""contents",
        "id" : 1 
        "password"123,
        "modifiedAt""createAt"

    }
    PUT /api/post/{id} {
    "username":"random"
    "content" : "content",
    "password" : "password"
    }
    {
       "username""name",
        "contents""contents",
        "id" : 1 
        "password"123,
        "modifiedAt""createAt"

    }
    DELETE /api/post/{id} {
    "username":"random"
    "content" : "content",
    "password" : "password"
    }
    {
      "success" : true
    }
    {
      "success" : false
    }

     

    코드 순서 (대략)

    고객 -> Dto -> Controller -> Service -> Entity -> Repository

     

    Service 클래스에서 CRUD메서드 만들어주기

     

    Controller

     

    @RestController :@Controller와 @ResponseBody가 합쳐짐  // 이 클래스가 Controlle인걸 나타냄

    @RequiredArgsConstructor :Lombok 어노테이션 중 하나로, 해당 클래스의 final 필드나 @NonNull 어노테이션이 붙은 필드에 대해 생성자를 자동으로 생성합니다.

     

    @GetMapping   : GET방식으로 받음

    @PostMapping : Post방식으로 받음

    @PutMapping   : 수정시 쓰임

    @DeleteMapping : 삭제시쓰임

     

    @PathVariable   :  url로 데이터를 가져옴

    @Requestparm  : url로 쿼리 방식으로 가져옴 

    @ModelAttribute: 객체형식으로 받음(key-value방식)

    @RequestBody  : Json형식으로 받음


    Service

     

    @Serice : 이 클래스가 Service인걸 나타냄

    @RequiredArgsConstructor : Lombok 어노테이션 중 하나로, 해당 클래스의 final 필드나 @NonNull 어노테이션이 붙은 필드에 대해 생성자를 자동으로 생성합니다

     

    @Transctional  : Spring에서 제공하는 어노테이션 중 하나로, 메소드나 클래스에 적용하여 데이터베이스 트랜잭션 처리를 지원합니다.

     


    Dto

     

    @Getter  : get메서드 자동 생성

    @Satter : set메서드 자동 생성 (거의 DB에 저장 안할때 사용)


    Entity

     

    @Getter

    @Entity   :  이 클래스가 Entity인걸 나타냄

    @NoArgsConstructor  :기본생성자 자동생성

     


    Repository

     

    인터페이스로 생성

    인터페이스 이름 뒤에 extends JpaRepository<Entity이름, Id타입>{

     

    List<Entity이름> findAllByOrderByModifiedAtDesc();     //시간별로 오름차순

    }

     

     

    Entity를 그대로 반환하지 않고 Dto에 담아서 반환하기

     

    @Service
    public class UserService {
        private final UserRepository userRepository;
        
        public UserService(UserRepository userRepository) {
            this.userRepository = userRepository;
        }
        
        public List<UserDto> getUsers() {
            List<User> userList = userRepository.findAll();
            
            List<UserDto> userDtoList = new ArrayList<>();
            for (User user : userList) {
                UserDto userDto = new UserDto();
                userDto.setId(user.getId());
                userDto.setName(user.getName());
                userDto.setEmail(user.getEmail());
                
                userDtoList.add(userDto);
            }
            
            return userDtoList;
        }
    }

     

     

    ResponseDto와 RequestDto를 나누지 말고 하나의 Dto만 만들고 @Jsonlgnore선언

     

    @JsonIgnore는 자바에서 사용되는 어노테이션으로, JSON 직렬화 및 역직렬화 중에 속성 또는 필드를 무시하는 데 사용됩니다. 객체를 JSON으로 직렬화 할 때 @JsonIgnore로 주석 처리된 속성 또는 필드는 결과 JSON 출력에서 제외됩니다. 마찬가지로 JSON을 객체로 역직렬화 할 때도 @JsonIgnore로 주석 처리된 속성 또는 필드는 무시됩니다.

    이 어노테이션은 특정 필드가 JSON 출력에서 제외되도록하거나, 역직렬화 할 때 해당 필드를 무시하도록 하는 상황에서 유용할 수 있습니다.

     

     

     

     

Designed by Tistory.