-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathUserService.java
63 lines (51 loc) · 1.93 KB
/
UserService.java
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
55
56
57
58
59
60
61
62
63
package com.music.review.app.services;
import com.music.review.app.domain.entities.users.User;
import com.music.review.app.domain.entities.users.dtos.UserCreateDTO;
import com.music.review.app.domain.entities.users.dtos.UserGetDTO;
import com.music.review.app.domain.entities.users.dtos.UserUpdateDTO;
import com.music.review.app.domain.repositories.UserRepository;
import jakarta.persistence.EntityNotFoundException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.util.List;
import java.util.stream.Collectors;
@Service
public class UserService {
private final UserRepository userRepository;
@Autowired
public UserService(UserRepository userRepository){
this.userRepository = userRepository;
}
@Transactional
public UserGetDTO saveUser(UserCreateDTO userCreateDTO){
User user = new User(userCreateDTO);
this.userRepository.save(user);
return new UserGetDTO(user);
}
public User findById(Long id){
return this.userRepository.getReferenceById(id);
}
public User findByEmail(String email){
User user = this.userRepository.getUserByEmail(email);
if (user == null) throw new EntityNotFoundException();
return user;
}
public List<UserGetDTO> findAll(){
List<User> users = this.userRepository.findAll();
return users.stream()
.map(UserGetDTO::new)
.collect(Collectors.toList());
}
@Transactional
public void deleteById(Long id){
this.userRepository.deleteById(id);
}
@Transactional
public UserGetDTO update(UserUpdateDTO userUpdateDTO){
User user = this.userRepository.getReferenceById(userUpdateDTO.id());
user.updateUser(userUpdateDTO);
this.userRepository.save(user);
return new UserGetDTO(user);
}
}