REST API 옮기기1-1: User Repository, Service, Controller 작동 확인하기

dev_314·2022년 8월 26일
0

JPA - Trial and Error

목록 보기
6/16

User Repository

package wonju.howcook.repository;

import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Repository;
import wonju.howcook.domain.User;

import javax.persistence.EntityManager;
import java.util.List;

@Repository
@RequiredArgsConstructor
public class UserRepository {
    private final EntityManager em;

	...
    
    public List<User> findByNickname(String nickname) {
        return em.createQuery("select u from User as u where u.nickname like '%:nickname%'")
                .setParameter(nickname, nickname)
                .getResultList();
    }
}

User Service

package wonju.howcook.service;

import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import wonju.howcook.domain.User;
import wonju.howcook.dto.user.UpdateUserDto;
import wonju.howcook.repository.UserRepository;

import javax.persistence.EntityNotFoundException;
import java.util.List;

@Service
@RequiredArgsConstructor
@Transactional
public class UserService {
    private final UserRepository userRepository;

    public List<User> findByNickname(String nickname) {
        return userRepository.findByNickname(nickname);
    }

	...
    
}

User Controller

package wonju.howcook.controller;

import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import wonju.howcook.domain.User;
import wonju.howcook.service.UserService;

import java.util.List;

@RestController
@RequiredArgsConstructor
@Slf4j
public class UserController {

    private final UserService userService;

    @GetMapping("/api/users/search")
    public List<User> findByNickname(@RequestParam String nickname) {
        log.info("nickname={}",nickname);
        return userService.findByNickname(nickname);
    }
}

Trial and Error

Controller - Service - Repository가 잘 연결되었는지 확인하기 위해 Postman으로 요청을 보냈다. (닉네임으로 유저 검색)

문제1. 파라미터를 찾지를 못한다.

해결1. 파라미터를 다시 설정했다.

    public List<User> findByNickname(String nickname) {
        return em.createQuery("select u from User as u where u.nickname like '%:nickname%'")
                .setParameter("nickname", nickname)
                .getResultList();
    }

문제2. 파라미터를 인식하질 못한다.

해결2. Like 구문이 포함된 JPQL을 수정했다.

    public List<User> findByNickname(String nickname) {
        return em.createQuery("select u from User as u where u.nickname like :nickname")
                .setParameter("nickname", "%" + nickname + "%")
                .getResultList();
    }
profile
블로그 이전했습니다 https://dev314.tistory.com/

0개의 댓글