spring data JPA 模糊查询 --- 使用 LIKE --- 的写法

方法一
1.  Controller层:
方法参数一定要加 "%"+name+"%"

@RestController
public class UserController {

    @Autowired
    private TeamRepository teamRepository;

    @GetMapping("/findByNameLike")
    public List<Team> findByNameLike(String name) {
        // 一定要加 "%"+参数名+"%"
        return teamRepository.findByNameLike("%"+name+"%");
    }
}

2. Dao层:
 一定要使用 JPA 规定的形式 findBy + 参数名 + Like(参数)

public interface TeamRepository extends JpaRepository<Team, String> {
    List<Team> findByNameLike(String name);

方法二
1. Controller:

参数简单化

@RestController
public class UserController {

    @Autowired
    private TeamRepository teamRepository;

    @GetMapping("/findByNameLike")
    public List<Team> findByNameLike(String name) {
        return teamRepository.findByNameLike(name);
    }
}

2.Dao层:
自己定义 SQL 语句

/** 参数1 就是 ?1 ,参数2 就是 ?2   */
public interface TeamRepository extends JpaRepository<Team, String> {
    @Query(value = "select t from Team t where t.name like '%?1%'")
    List<Team> findByNameLike(String name);


原文地址: https://www.cnblogs.com/yang1314/p/9295764.html

猜你喜欢

转载自blog.csdn.net/beguile/article/details/88531126