首页 > 技术文章 > 【JPA】 @query上使用if判断

zzsuje 2020-10-29 18:01 原文

 
  1. @Query(value = "select * from xxx where if(?1 !='',x1=?1,1=1) and if(?2 !='',x2=?2,1=1)" +
  2. "and if(?3 !='',x3=?3,1=1) ",nativeQuery = true)
  3. List<XXX> find(String X1,String X2,String X3);

工作的时候需求有搜索功能,有三个参数,但是网上找了很多关于jpa多条件查询的代码要么在调dao的时候用了大量if判断,那么需要写很多查询方法,要么说的不知所云,我结合jpa和mysql原语句研究了半天才弄出了这个方法。

xxx是数据库表名,x1、x2、x3为查询的字段名。

下面的大写的XXX是实体类的名,X1X2X3为查询的参数。

if(?1 !='',x1=?1,1=1) 代表传入的参数X1如果不为""(Spring类型空是""而不是null)将参数传入x1,如果为空时显示1=1 代表参数为真,对查询结果不产生作用。

 

 

 

在使用spring boot JPA写repository的时候参数可能为空不传

  1. @Query(value = "select * from mw_user where is_identification = 1 and is_inter_identification = 1 and if(?1 !='',mobile=?1,1=1) and if(?2 !='',nick=?2,1=1)",nativeQuery = true)
  2. List<MwUser> findBySearch(String mobile,String nick);
  3.  

利用原生sql 加 if的方式实现参数为空不作为查询条件

 

@Query(value = "select * from mw_user where is_identification = 1 and is_inter_identification = 1  and if(?1 !='',mobile=?1,1=1) and if(?2 !='',nick  LIKE CONCAT('%',?2,'%'),1=1)",nativeQuery = true)
List<MwUser> findBySearchTotal(String mobile,String nick);
@Query(value = "select count(1) from mw_user where mw_user.is_identification='1' and mw_user.is_inter_identification='1' and if(?1 !='',mobile=1?,1=1) and if(?2 !='',nick LIKE CONCAT('%',?2,'%'),1=1)",nativeQuery = true)
Long findBySearchTotalCount(String mobile,String nick);

 

三种方式解决,

一、使用:name

+ "WHERE IF (:byname is not null, c.byname LIKE CONCAT('%',:byname,'%') , 1 = 1) and IF (:isMember is not null, c.is_member = :isMember , 1 = 1) and IF (:isBlacklist is not null, c.is_blacklist = :isBlacklist , 1 = 1) and "
+ "IF (:phone is not null, c.phone = :phone , 1 = 1)"
+ "GROUP BY c.id LIMIT :PageOne,:PageSize",nativeQuery=true)
List<Map<String, Object>> countByQuery(@Param("byname") String byname,@Param("isMember") Integer isMember,@Param("isBlacklist") Integer isBlacklist,@Param("phone") String phone,@Param("PageOne") Integer PageOne, @Param("PageSize")Integer PageSize);

转载自:https://www.cnblogs.com/laixin09/p/9776868.html

二、使用1,2,3方式

 

//jpa 多对多关系的表联合查询 DAO层
@Query(value = "select s from SysUserDTO s left join s.sysOrgDTOSet o where (?1 is null or s.username like ?1) and (?2 is null or o.name like ?2)")
    Page<SysUserDTO> findByUsernameAndOrgName(String username, String orgName, Pageable pageable);
// service层
public Page<SysUserDTO> findByUsernameAndOrgName(String username, String orgName, Pageable pageable){
        String name = (username==null)?null:"%"+username+"%";
        String orgname = (orgName==null)?null:"%"+orgName+"%";
        return sysUserDAO.findByUsernameAndOrgName(name,orgname,pageable);
三:一二结合

@Query(value = "select * from xxx where if(?1 !='',x1=?1,1=1) and if(?2 !='',x2=?2,1=1)" +
            "and if(?3 !='',x3=?3,1=1)  ",nativeQuery = true)
     List<XXX> find(String X1,String X2,String X3);

推荐阅读