首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >专栏 >史上最全的SpringBoot | JPA基本查询SQL

史上最全的SpringBoot | JPA基本查询SQL

作者头像
用户1750537
发布2025-08-29 09:12:05
发布2025-08-29 09:12:05
7800
代码可运行
举报
运行总次数:0
代码可运行

一、JPA 基本查询 Spring Data JPA提供的一个查询规范,查询语句关键字,简单的SQL可根据方法命名来即可,省略了写sql语句。

代码语言:javascript
代码运行次数:0
运行
复制
关键字                    方法命名                                 sql where字句
And                     findByNameAndPwd                    where name= ? and pwd =?
Or                      findByNameOrSex                     where name= ? or sex=?
Is,Equals               findById,findByIdEquals             where id= ?
Between                 findByIdBetween                     where id between ? and ?
LessThan                findByIdLessThan                    where id < ?
LessThanEquals          findByIdLessThanEquals              where id <= ?
GreaterThan             findByIdGreaterThan                 where id > ?
GreaterThanEquals       findByIdGreaterThanEquals           where id > = ?
After                   findByIdAfter                       where id > ?
Before                  findByIdBefore                      where id < ?
IsNull                  findByNameIsNull                    where name is null
isNotNull,NotNull       findByNameNotNull                   where name is not null
Like                    findByNameLike                      where name like ?
NotLike                 findByNameNotLike                   where name not like ?
StartingWith            findByNameStartingWith              where name like ‘?%’
EndingWith              findByNameEndingWith                where name like ‘%?’
Containing              findByNameContaining                where name like ‘%?%’
OrderBy                 findByIdOrderByXDesc                where id=? order by x desc
Not                     findByNameNot                       where name <> ?
In                      findByIdIn(Collection<?> c)         where id in (?)
NotIn                   findByIdNotIn(Collection<?> c)      where id not in (?)
True                    findByAaaTue                        where aaa = true
False                   findByAaaFalse                      where aaa = false
IgnoreCase              findByNameIgnoreCase                where UPPER(name)=UPPER(?)

二、JPA 多条件查询(参数为空判断)语句 搜索:@Query参数为空 三种方式解决,

  1. 使用:name
代码语言:javascript
代码运行次数:0
运行
复制
 "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);
  1. 使用1,2,3方式

//jpa 多对多关系的表联合查询 DAO层

代码语言:javascript
代码运行次数:0
运行
复制
@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);

3 .一二结合

@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 find(String X1,String X2,String X3); 工作中遇到一个多条件查询的需求,需要根据名字,性别, 年龄以及序号查询数据,名字需要模糊查询,参数有可能为空。

代码语言:javascript
代码运行次数:0
运行
复制
@Query(value = "select * from people where if(?1 !='',name like concat('%',?1,'%'),1=1) and if(?2 !='',sex=?2,1=1)"+
" and if(IFNULL(?3,'') !='',age=?3,1=1) and if(IFNULL(?4,'') !='',num=?4,1=1) ",nativeQuery = true)
List<People> find(String name,String sex,Integer age,Integer num);

nativeQuery = true 的含义是使用原生SQL,即注解中的SQL语句会生效,false的话就不会生效。 SQL语句中 ?1、?2、?3、?4 的意思是代表方法中的第几个参数。 SQL中模糊查询的写法为 like concat(‘%’, ?1, ‘%’) if(?1 !=‘’,name like concat(‘%’,?1,‘%’),1=1) 代表传入的参数name如果不为"“(Spring类型空是”"而不是null)将参数传入name,如果为空时显示1=1 代表参数为真,对查询结果不产生作用。IF 的语法满足mysql的基本语法,IF(expr1,expr2,expr3), 如果 expr1 为真(expr1 <> 0 以及 expr1 <> NULL),那么 IF() 返回 expr2,否则返回expr3 if(IFNULL(?3,‘’) !=‘’,age=?3,1=1) 表示如果传入的年龄是null,则替换成空字符串,然后判断是否为空,不为空则将参数传入age,否则忽略不对查询结果产生影响。IFNULL 是mysql中的一个函数,这个函数一般用来替换 NULL 值的。IFNULL(value1,value2),判断value1是否为null,如果为null则用value2替换。 参数定义时,定义数值,应使用Integer,如果用int定义,当入参为NULL时,程序会报空指针错误。原因是JAVA 中 int 是值类型,非对象,不可以设置为 NULL,integer 是对象类型,可以设置为NULL

三、jpa @Query中使用in,需要注意参数一定要是List<>,不然无法查询出数据。

代码语言:javascript
代码运行次数:0
运行
复制
@Query(value = "select * from trade$seek_purchase_offer where sp_id in (:spIds) and of_enuu = :enUu", nativeQuery = true)
    List<SeekPurchaseOffer> getSeekPurchaseOfferList(@Param("spIds") List<Long> spIds, @Param("enUu") Long enUu);
本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2023-07-17,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档