我如何使用 sql 与 Java Spring 的多对一查询?

How can i use many to one sql query with Java Spring?

我正在尝试做一个搜索栏。这个搜索栏必须找到有自己名字或主人名字的动物。 Animal table 有 user_id 作为外键。我必须找到动物的所有者名称,因为我认为将用户 table 加入动物。我使用 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);
    }

animal table users table

所有代码在这里:https://github.com/Furkan-Ahmet-Ozdemir/Spring-vet

** 已解决:“select a.* 来自 animals a inner join users u on u.id=a.user_id where a.name like %:keyword% or u.first_name 喜欢 %:keyword%" **

请试试这个

@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)