티스토리 뷰
● 유저 생성 API
[API Specification(API 명세)]
1. HTTP Method → POST
2. HTTP Path → /user
3. HTTP Body(JSON) → { “name”: String(필수 O), “age”: Integer(필수 X) } / 이름은 필수, 나이는 선택
4. API 반환 결과(값) → 없음, (HTTP code = 200)이면 정상 처리 판정
[Controller]
package com.group.libraryapp.controller.user;
import com.group.libraryapp.domain.user.User;
import com.group.libraryapp.dto.user.request.UserCreateRequest;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;
import java.util.ArrayList;
import java.util.List;
@RestController
public class UserController {
private final List<User> users = new ArrayList<User>();
@PostMapping("/user")
public void saveUser(@RequestBody UserCreateRequest request) {
users.add(new User(request.getName(), request.getAge()));
}
}
- User 객체를 만들어서 유저 정보를 저장할 것이다.
[domain]
package com.group.libraryapp.domain.user;
public class User {
private String name;
private Integer age;
public User(String name, Integer age) {
if(name == null || name.isBlank()) throw new IllegalArgumentException(String.format("잘못된 name(%s)이 들어왔습니다.", name));
this.name = name;
this.age = age;
}
}
- UserController의 saveUser 메소드에 @RequestBody Annotation이 있기에 DTO에는 별도의 Constructor가 필요없다.
- Constructor가 있어도 상관은 없다.
[DTO]
package com.group.libraryapp.dto.user.request;
public class UserCreateRequest {
private String name; // 이름은 필수
private Integer age; // 나이는 선택, int는 기본형(Primitive type)이므로 null 값을 가질 수 없다.
public String getName() {
return name;
}
public int getAge() {
return age;
}
}
cf1)
- 단, 현재 단계에서 생성된 유저 데이터는 서버를 재시작하면 사라진다.
- 이는 유저 데이터가 메모리에서만 유지되고 있기 때문이다.
- 그래서 DB를 사용하는 것이다.
cf2) int 대신 Integer를 선언한 이유
- Java에서 int 같은 Primitive type은 null 값을 가질 수 없다. 대신 Integer 같은 Reference Type은 null 값을 가질 수 있다.
- Primitive type은 실제 값을 메모리에 저장하고 Reference Type은 객체의 주소값을 저장하기에 null 값을 가질 수 있는 것(실제 값을 저장하느냐 실제 값을 가르키는 주소값을 저장하느냐의 차이)
- 따라서 나이는 필수로 넘어오는 값이 아니므로 null 값을 담기 위해 int 대신 Integer를 age 변수의 자료형으로 설정했다.
int 에는 null 값이 들어갈 수 없는데 Integer 에는 null 값이 들어갈 수 있는 이유는 뭔가요?
wrapper 클래스를 공부하다 궁금점이 생겨서 질문합니다.
qna.programmers.co.kr
'Backend > Spring' 카테고리의 다른 글
#11 MySQL - CREATE TABLE (0) | 2023.08.13 |
---|---|
#10 유저 조회 API (0) | 2023.08.12 |
#8 GET API의 DTO와 POST API의 DTO가 차이가 나는 이유 (0) | 2023.08.09 |
#7 DTO와 VO(Entity는 링크한 글을 보자) (0) | 2023.08.04 |
#6 POST API (0) | 2023.07.31 |
- Total
- Today
- Yesterday
- 자료구조
- 프로그래머스
- nosql
- db
- 빅데이터 분석기사
- jpa
- git
- DART
- 운영체제
- Stream
- 프로세스
- API
- 메모리
- spring
- Advanced Stream
- 코테
- 빅데이터
- MongoDB
- Phaser
- MySQL
- java
- OS
- Java8
- SQL
- 코딩테스트
- SpringBoot
- 알고리즘
- Spring Boot
- node.js
- Phaser3
일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
1 | 2 | 3 | 4 | 5 | ||
6 | 7 | 8 | 9 | 10 | 11 | 12 |
13 | 14 | 15 | 16 | 17 | 18 | 19 |
20 | 21 | 22 | 23 | 24 | 25 | 26 |
27 | 28 | 29 | 30 |