Issue
I want to implement a search by category and keyword, but the query returns an empty list. I know that you can make several methods for requests, but I would like to fit this into one method. Please tell me how to do this correctly
Repository:
@Repository
public interface UserRepository extends JpaRepository<User, Long> {
User findByEmail(String email);
User findByNickname(String nickname);
User findByPhone(String phoneNumber);
@Query(value = "SELECT * FROM users WHERE :filter LIKE CONCAT('%',:keyword,'%')",
nativeQuery=true)
List<User> findByKeyword(@Param("filter") String filter,
@Param("keyword") String keyword);
}
Controller:
@Controller
@RequestMapping("/admin")
public class AdminController {
@Autowired
private UserService userService;
@Autowired
private OrderService orderService;
@GetMapping("/users")
public String index(Model model, Principal user,
String keyword, String filter){
model.addAttribute("user",
userService.findUserByNickname(user.getName()));
if(keyword!=null){
model.addAttribute("users",
userService.getUsersByKeyword(filter, keyword));
return "admin/index";
}
model.addAttribute("users", userService.findAll());
return "admin/index";
}
}
HTML:
<form th:action="@{/admin/users}" method="get">
<input type="text" name="keyword">
<input type="checkbox" name="filter" value="id"><label>ID</label>
<input type="checkbox" name="filter" value="nickname"><label>NAME</label>
<input type="checkbox" name="filter" value="phone"><label>PHONE</label>
<input type="checkbox" name="filter" value="email"><label>EMAIL</label>
<button type="submit">Go</button>
</form>
Service:
public List<User> getUsersByKeyword(String filter, String keyword){
return userRepository.findByKeyword(filter,keyword);
}
Solution
You could use a specification: https://spring.io/blog/2011/04/26/advanced-spring-data-jpa-specifications-and-querydsl/
Just let your repository extend JpaSpecificationExecutor<T>
:
public interface UserRepository extends JpaRepository<User, Long>,
JpaSpecificationExecutor<User> {
}
And query by specification:
String column = "myColumn"; // user-supplied
String value = "myValue"; // user-supplied
Specification<User> spec = (root, query, criteriaBuilder) ->
criteriaBuilder.like(root.get(column), "%" + value + "%");
var result = repo.findAll(spec);
Answered By - fladdimir
Answer Checked By - Marie Seifert (JavaFixing Admin)