본문 바로가기
Kotlin

Java Service코드를 Kotlin Service코드로..

by jisung-kim 2024. 1. 8.

 

UserService.java

@Service
public class JavaUserService {

  private final UserRepository userRepository;

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

  @Transactional
  public void saveUser(UserCreateRequest request) {
    User user = new User(request.getName(), request.getAge(), Collections.EMPTY_LIST,null);
    userRepository.save(user);
  }

  @Transactional(readOnly = true)
  public List<UserResponse> getUsers() {
    return userRepository.findAll().stream()
        .map(UserResponse::new)
        .collect(Collectors.toList());
  }

  @Transactional
  public void updateUserName(UserUpdateRequest request) {
    User user = userRepository.findById(request.getId()).orElseThrow(IllegalArgumentException::new);
    user.updateName(request.getName());
  }

  @Transactional
  public void deleteUser(String name) {
    User user = userRepository.findByName(name);
    userRepository.delete(user);
  }

}

 

 

UserService.kt

@Service
class UserService(
    private val userRepository: UserRepository

) {
    @Transactional
    fun saveUser(request: UserCreateRequest){
        val newUser = User(request.name, request.age)
        userRepository.save(newUser)
    }

    @Transactional(readOnly = true)
    fun getUsers(): List<UserResponse>{
        return userRepository.findAll()
            .map { UserResponse.of(it) }
    }

    @Transactional
    fun updateUserName(request: UserUpdateRequest){
        val user = userRepository.findByIdOrThrow(request.id)
        user.updateName(request.name)
    }

    @Transactional
    fun deleteUser(name: String){
        val user = userRepository.findByName(name) ?: fail()
        userRepository.delete(user)
    }
}

이번에 주목해야할점은 getUsers() 함수이다.  

함수 getUsersList<UserResponse>를 반환하는 형태로 선언되어 있다

findAll()이 반환하는 리스트에 대해 map 함수를 사용하여 각각의 User 객체를 UserResponse 객체로 변환한다.

 UserResponse 클래스의 of 함수를 사용한다.

 

'Kotlin' 카테고리의 다른 글

Java Entity코드를 Kotlin Entity로..  (0) 2024.01.09
Java Controller를 Kotlin Controller로  (1) 2024.01.08
JAVA DTO를 Kotlin DTO로..  (0) 2024.01.08