1. 程式人生 > 實用技巧 >jpa @query上使用if判斷

jpa @query上使用if判斷

2019-07-15 09:15:37 15025 收藏 3 分類專欄: Spring,SpringBoot
  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 代表引數為真,對查詢結果不產生作用。

jpa 條件不為空加 條件查詢

2019-03-29 16:32:09 11262 收藏 4 分類專欄: 問題方案 文章標籤: jpa 條件不為空加 條件查詢 sql條件不為空加 條件查詢 版權

在使用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);

利用原生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);

Spring Data JPA中@Query引數為空處理方式

2019-07-19 16:51:35 8381 收藏 3

搜尋:@Query引數為空

三種方式解決,

一、使用:name

+ "WHEREIF (: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="selectsfromSysUserDTOsleftjoins.sysOrgDTOSetowhere(?1isnullors.usernamelike?1)and(?2isnulloro.namelike?2)")
Page<SysUserDTO>findByUsernameAndOrgName(Stringusername,StringorgName,Pageablepageable);
//service層
publicPage<SysUserDTO>findByUsernameAndOrgName(Stringusername,StringorgName,Pageablepageable){
Stringname=(username==null)?null:"%"+username+"%";
Stringorgname=(orgName==null)?null:"%"+orgName+"%";
returnsysUserDAO.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);