[250319] TIL
์ค๋ ํ ์ผ
์ด๋ ธํ ์ด์ ๊ณต๋ถ
์ด๋ ธํ ์ด์
@NoArgsConstructor
- ํ๋ผ๋ฏธํฐ๊ฐ ์๋ ๊ธฐ๋ณธ ์์ฑ์๋ฅผ ์์ฑ
@NoArgsConstructor(access = AccessLevel.*PROTECTED*)
- ์ธ๋ถ์์ ์์ฑ์ ์ ๊ทผ ๋ถ๊ฐ๋ฅํ๋๋ก ๋ง๋ฌ
- ์์ ๋ฐ์์๋ ์ฌ์ฉ ๊ฐ๋ฅํ๋๊น, JPA๋ ์ฌ์ฉ ๊ฐ๋ฅํจ
@Entity
@NoArgsConstructor(access = AccessLevel.PROTECTED) // JPA๋ฅผ ์ํ ๊ธฐ๋ณธ ์์ฑ์
public class Order {
@Id @GeneratedValue
private Long id;
@ManyToOne
private User user;
private int totalAmount;
private OrderStatus status;
// ์๋๋ ์์ฑ ๋ฐฉ๋ฒ์ ๊ฐ์ ํ๋ ์์ฑ์
@Builder
public Order(User user, int totalAmount) {
this.user = user;
this.totalAmount = totalAmount;
this.status = OrderStatus.PENDING;
}
}
// ์ฌ์ฉํ๋ ๊ณณ์์
// ์๋ชป๋ ๋ฐฉ๋ฒ (์ปดํ์ผ ์๋ฌ)
Order order = new Order(); // protected ์์ฑ์๋ผ์ ์ ๊ทผ ๋ถ๊ฐ
// ์ฌ๋ฐ๋ฅธ ๋ฐฉ๋ฒ
Order order = Order.builder()
.user(user)
.totalAmount(10000)
.build();
@RequiredArgsConstructor
- final ํ๋๋ @NonNull ๋ก ํ์๋ ํ๋๋ง์ ํ๋ผ๋ฏธํฐ๋ก ๋ฐ๋ ์์ฑ์๋ฅผ ์์ฑํจ.
// @RequiredArgsConstructor ์ฌ์ฉ ์
public class UserService {
private final UserRepository userRepository;
private final PasswordEncoder passwordEncoder;
// ์ง์ ์์ฑํ ์์ฑ์
public UserService(UserRepository userRepository, PasswordEncoder passwordEncoder) {
this.userRepository = userRepository;
this.passwordEncoder = passwordEncoder;
}
}
// @RequiredArgsConstructor ์ฌ์ฉ ํ
@RequiredArgsConstructor
public class UserService {
private final UserRepository userRepository;
private final PasswordEncoder passwordEncoder;
// Lombok์ด ์๋์ผ๋ก final ํ๋๋ค์ ํ๋ผ๋ฏธํฐ๋ก ๋ฐ๋ ์์ฑ์ ์์ฑ
}
@RequestBody
- HTTP ์์ฒญ์ ๋ณธ๋ฌธ์ ์๋ฐ ๊ฐ์ฒด๋ก ๋ณํํ๋ ๋ฐ ์ฌ์ฉ
@PostMapping
public ResponseEntity<ApiResponse> createUser(@RequestBody UserRequestDto requestDto) {
// requestDto๋ ํด๋ผ์ด์ธํธ๊ฐ ๋ณด๋ธ JSON ๋ฐ์ดํฐ๋ฅผ ๊ธฐ๋ฐ์ผ๋ก ์์ฑ๋ ๊ฐ์ฒด์
๋๋ค.
// ์ฌ๊ธฐ์ requestDto๋ฅผ ์ฌ์ฉํ์ฌ ์ฌ์ฉ์ ์์ฑ ๋ก์ง์ ๊ตฌํํ ์ ์์ต๋๋ค.
}
N+1 ๋ฌธ์
- ํ ๋ฒ์ ์ฟผ๋ฆฌ๋ก ๋ฐ์ดํฐ๋ฅผ ๋ถ๋ฌ์๋๋ฐ, N๋ฒ์ ์ฟผ๋ฆฌ๊ฐ ๋ ์คํ ๋๋ ๋ฌธ์
Leave a comment