๐งฑ 1. Controller (์ปจํธ๋กค๋ฌ)
๐ ์ญํ
- ์ฌ์ฉ์์ ์์ฒญ์ ๋ฐ์์ ์ฒ๋ฆฌํ๋ ์ ๊ตฌ ์ญํ
- ์ฃผ๋ก HTTP ์์ฒญ(GET, POST, PUT, DELETE)์ ๋ฐ๊ณ ,
- ์์ฒญ์ ์ฒ๋ฆฌํ Service๋ฅผ ํธ์ถํ๊ณ ,
- ๊ฒฐ๊ณผ๋ฅผ ํด๋ผ์ด์ธํธ์๊ฒ ์๋ต์ผ๋ก ๋ฐํํจ.
๐ฏ ์ฌ์ฉ ์
@RestController
@RequestMapping("/users")
public class UserController {
private final UserService userService;
public UserController(UserService userService) {
this.userService = userService;
}
@GetMapping("/{id}")
public UserDto getUser(@PathVariable Long id) {
return userService.getUserById(id);
}
}
๐ง 2. Service (์๋น์ค)
๐ ์ญํ
- ๋น์ฆ๋์ค ๋ก์ง์ด ๋ค์ด์๋ ์ค๊ฐ ๊ด๋ฆฌ์
- ๋ฐ์ดํฐ ์ฒ๋ฆฌ ์์, ๊ณ์ฐ, ๊ฒ์ฆ ๋ฑ ์ฃผ์ ๋ก์ง ์ํ
- ์ปจํธ๋กค๋ฌ๋ ์๋น์คํํ "์ด๊ฑฐ ํด์ค"๋ผ๊ณ ์์ฒญํจ
- ์๋น์ค๋ DB์ ์ง์ ์ ์ดํ์ง ์๊ณ Repository๋ฅผ ํธ์ถํจ
๐ฏ ์ฌ์ฉ ์
@Service
public class UserService {
private final UserRepository userRepository;
public UserService(UserRepository userRepository) {
this.userRepository = userRepository;
}
public UserDto getUserById(Long id) {
User user = userRepository.findById(id)
.orElseThrow(() -> new RuntimeException("User not found"));
return new UserDto(user.getId(), user.getName());
}
}
๐๏ธ 3. Repository (๋ ํฌ์งํ ๋ฆฌ)
๐ ์ญํ
- DB์ ์ง์ ์ ๊ทผํด์ ๋ฐ์ดํฐ๋ฅผ ๊ฐ์ ธ์ค๊ฑฐ๋ ์ ์ฅํ๋ ๊ณ์ธต
- ๋ณดํต JPA, MyBatis, JDBC ๋ฑ์ ์ฌ์ฉํด์ ๊ตฌํ
- ์ธํฐํ์ด์ค๋ง ๋ง๋ค์ด๋ JPA๊ฐ ์์์ ๊ตฌํํด์ค
๐ฏ ์ฌ์ฉ ์
@Repository
public interface UserRepository extends JpaRepository<User, Long> {
// ํ์ํ ๊ฒฝ์ฐ ์ปค์คํ
์ฟผ๋ฆฌ๋ ์ถ๊ฐ ๊ฐ๋ฅ
Optional<User> findByEmail(String email);
}
๐งฌ 4. Domain (๋๋ฉ์ธ)
๐ ์ญํ
- **๋น์ฆ๋์ค ๋์์ด ๋๋ ์ค์ ๊ฐ์ฒด(์ํฐํฐ)**๋ฅผ ํํํ๋ ํด๋์ค
- ์: User, Product, Order ๊ฐ์ ์ค์ ๋น์ฆ๋์ค ๊ฐ์ฒด๋ค
- DB ํ ์ด๋ธ๊ณผ ๋งคํ๋๋ฉฐ, JPA์์ @Entity๋ก ํ์ํจ
๐ฏ ์ฌ์ฉ ์
@Entity
public class User {
@Id @GeneratedValue
private Long id;
private String name;
private String email;
// getter, setter, ์์ฑ์ ๋ฑ ์๋ต
}
๐ ์ ์ฒด ํ๋ฆ ์์ฝ
[Client] → ์์ฒญ
↓
[Controller] → ์์ฒญ ํ๋ผ๋ฏธํฐ ๋ฐ๊ณ , Service ํธ์ถ
↓
[Service] → ๋น์ฆ๋์ค ๋ก์ง ์ํ, Repository ํธ์ถ
↓
[Repository] → DB์์ ๋ฐ์ดํฐ ์กฐํ or ์ ์ฅ
↓
[Domain] → ์ค์ ๋ฐ์ดํฐ ๊ฐ์ฒด(Entity)
↓
๊ฒฐ๊ณผ๋ฅผ ๋ค์ ์๋ก ๋ฐํ → ์ต์ข
์๋ต
๐ก ์ค์ ์: ์ ์ ์กฐํ API
[๋ธ๋ผ์ฐ์ ์์ฒญ] GET /users/1
↓
[UserController] → userService.getUserById(1)
↓
[UserService] → userRepository.findById(1)
↓
[UserRepository] → DB์์ User ์ํฐํฐ ์กฐํ
↓
[User] → ์ํฐํฐ → DTO๋ก ๋ณํ → ํด๋ผ์ด์ธํธ์๊ฒ ์๋ต
๐ ์ ๋ฆฌํ
๊ณ์ธต ์ญํ ์ค๋ช ์ด๋ ธํ ์ด์ ์ฃผ์ ํค์๋
| Controller | ์์ฒญ ์ฒ๋ฆฌ & ์๋ต ๋ฐํ | @Controller, @RestController | HTTP |
| Service | ๋น์ฆ๋์ค ๋ก์ง | @Service | ๋ก์ง |
| Repository | ๋ฐ์ดํฐ๋ฒ ์ด์ค ์ ๊ทผ | @Repository or JpaRepository | DB |
| Domain | DB ํ ์ด๋ธ๊ณผ ๋งคํ๋๋ ๋ชจ๋ธ ํด๋์ค | @Entity | ๊ฐ์ฒด |
'๐ฅ๏ธ ์น(Web) > ์คํ๋ง' ์นดํ ๊ณ ๋ฆฌ์ ๋ค๋ฅธ ๊ธ
| ์คํ๋ง Controller ์ฝ๋์์ Model์ ์ถ์ฒ์ ์ญํ (0) | 2025.04.18 |
|---|---|
| DTO, Entity, Mapper (0) | 2025.04.18 |
| ์คํ๋ง ๋ถํธ ํ๋ก์ ํธ ๊ตฌ์กฐ (0) | 2025.04.18 |
| ์คํ๋ง ๊ด๋ จ ํด (0) | 2025.04.18 |
| [์ดํด๋ฆฝ์ค] ์คํ๋ง ํ๋ก์ ํธ import ํ ๋ some project cannot be imported ์๋ฌ ๋ฐ์ (0) | 2025.04.17 |