JPA like 模糊查询 语法格式
public List<InstitutionInfo> getAllInstitution(final Application app){
String zdGljg = null;
Sysuser user = (Sysuser) app.getUser();
String userGljg = user.getGljg();
if("00".equals(userGljg.substring(4, 6))){//市级机构权限
zdGljg = userGljg.substring(0, 4) + "%";
}else if("00".equals(userGljg.substring(6, 8))){//区县级机构权限
zdGljg = userGljg.substring(0, 6) + "%";
}else{//乡镇级机构权限
zdGljg = userGljg + "%";
}
Query query = entityManager.createQuery("select s from InstitutionInfo s where s.gljg like :zdGlbh ");
query.setParameter("zdGlbh", zdGljg);
List<InstitutionInfo> adg =query.getResultList();
return adg;
}
模糊查询:Spring Data JPA 如何进行模糊查询(LIKE) ?
Spring MVC + Spring Data JPA+模糊查询
为了方便起见,service直接忽略,方便理解。
一. 方法一
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语句
public interface TeamRepository extends JpaRepository<Team, String> {
@Query(value = "select t from Team t where t.name like %?1%")
List<Team> findByNameLike(String name);
以上为个人经验,希望能给大家一个参考,也希望大家多多支持编程网。