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();
}
}
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);
}
...
}
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);
}
}
Controller - Service - Repository가 잘 연결되었는지 확인하기 위해 Postman으로 요청을 보냈다. (닉네임으로 유저 검색)
public List<User> findByNickname(String nickname) {
return em.createQuery("select u from User as u where u.nickname like '%:nickname%'")
.setParameter("nickname", nickname)
.getResultList();
}
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();
}