Issue
I am trying to make a search bar .This search bar must find animals with own name or owner name. Animal table have user_id as foreign key . I have to find animals with their owner name for that i think joining users table to animals .I use MySQL.
AnimalRepository.java
public interface AnimalRepository extends JpaRepository<Animal,Integer > {
public Long countById(Integer id);
@Query(value = "select * from animal join users where name like %:keyword% or where users.name like %:keyword%", nativeQuery = true)
List<Animal> findByKeyword(@Param("keyword") String keyword);
}
SearchPageController.java
@Autowired
private AnimalService animalService;
@RequestMapping(path = {"/","/search"})
public String home(Animal shop, Model model, String keyword) {
if(keyword!=null) {
List<Animal> list = animalService.getByKeyword(keyword);
model.addAttribute("list", list);
}else {
List<Animal> list = animalService.getAllAnimals();
model.addAttribute("list", list);}
return "index";
}
AnimalService.java
public List<Animal> getAllAnimals(){
List<Animal> list = (List<Animal>)repo.findAll();
return list;
}
public List<Animal> getByKeyword(String keyword){
return repo.findByKeyword(keyword);
}
All code here: https://github.com/Furkan-Ahmet-Ozdemir/Spring-vet
** SOLVED: "select a.* from animals a inner join users u on u.id=a.user_id where a.name like %:keyword% or u.first_name like %:keyword%" **
Solution
Please try this one
@Query(value = "select a.* from animal a inner join users u on u.id=a.user_id where a.name like %:keyword% or u.name like %:keyword%", nativeQuery = true)
Answered By - hkmaarouf
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.