MongoDB 2장 mlab 무료 클라우드

2장에 이어서 글을 간단 몽고 DB CRUD를 진행해보자

git-hub-code

3장 MongoDB 3장 간단 CRUD with Spring

1. UserRepository

아래처럼 findByUserIdAnd~~~ 이런식으로 하는 부분이.. 개인적으로 직관적이긴 하나 너무 길어지면 보기 힘들다 생각한다. 다음 4장에서 mongodb-query-dsl을 적용 할 예정

1
2
3
4
public interface UserRepository extends MongoRepository<UserCollection, String> {

Optional<UserCollection> findByUserId(String userId);
}

2. UserService

NotFoundException과 UniqueException은 CustomException임을 미리 공유

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
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
@Service
public class UserService {

private final UserRepository userRepository;

public UserService(UserRepository userRepository) {
this.userRepository = userRepository;
}

@Transactional
public void createUser(UserSignUpRequest req) {

userRepository
.findByUserId(req.getUserId())
.ifPresent(
user -> {
throw new UniqueException("already user");
});

final String id = req.getUserType() + UUID.randomUUID().toString();
UserCollection userCollection =
UserCollection.builder()
.id(id)
.userId(req.getUserId())
.userName(req.getUserName())
.email(req.getEmail())
.address(req.getAddress())
.age(req.getAge())
.build();

userRepository.save(userCollection);
}

public UserDto getUserData(String userId) {

UserCollection userCollection =
userRepository
.findByUserId(userId)
.orElseThrow(() -> new NotFoundException("user data is not found"));

return UserDto.toUserDto(userCollection);
}

@Transactional
public void deleteUser(String userId) {
UserCollection userCollection =
userRepository
.findByUserId(userId)
.orElseThrow(() -> new NotFoundException("user data is not found"));

userCollection.setIsDeleted(1);
userRepository.save(userCollection);
}
}

3. UserController

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
@RestController
@RequestMapping("/users")
public class UserController {
private final UserService userService;

public UserController(UserService userService) {
this.userService = userService;
}

@ResponseStatus(HttpStatus.CREATED)
@PostMapping
public void createUser(@RequestBody UserSignUpRequest userSignUpRequest) {

userService.createUser(userSignUpRequest);
}

@GetMapping
public UserDto user(@RequestParam("userId") String userId) {

return userService.getUserData(userId);
}

@ResponseStatus(HttpStatus.NO_CONTENT)
@DeleteMapping("/{userId}")
public void updateUser(@PathVariable("userId") String userId) {

userService.deleteUser(userId);
}
}

사실.. 딱히 쓸말이 없다 빠르게. 다음 4장에서 audit config 적용과 mongodb-querydsl을 적용해보자