标签:SpringData JPA 方法 入门 查询 规则 where id name
前言
本章讲解SpringData JPA有关于方法名称规则查询的相关知识
方法
1.概念
我们知道,Repository接口是我们的标识接口。但是其还含有另外的功能,那就是继承了该接口的Dao层接口类将拥有两种查询方式的支持:基于方法名称命名规则查询、基于@Query注解查询
本章我们先说第一种方式,也就是基于方法名称命名规则查询
2.方法名称规则
既然是基于方法命名规则,那么肯定有一套规则约束方法的命名:
findBy(关键字)+ 属性名称(首字母大写)+ 查询条件(首字母大写)
1)修改dao接口,加入如下方法
package cn.edu.ccut.dao;
import java.util.List;
import org.springframework.data.jpa.repository.JpaRepository;
import cn.edu.ccut.bo.Users;
/**
* 继承JpaRepository<T, ID>接口
* T传入当前操作的实体类,ID传入该类的主键类型
* @author jwang
*
*/
public interface UserDAO extends JpaRepository<Users, Integer>{
/**
* findBy+Username+查询条件(不写默认是相等条件)
* @param username
* @return
*/
public List<Users> findByUsername(String username);
}
该方法遵守我们的方法名称规则,使用该方法将查询出指定名称的用户!
service层接口编写:
测试代码编写:
测试运行结果:
这证明该方法成功的查询到了指定的数据!
当然,我这个方法命名的还是比较简单的,那么如果是比较复杂的查询呢,我们的方法名称将变得极其的长,这显然不利于我们的开发。也就是说,简单查询的时候,我们推荐使用该查询方法。
3.其他查询规则命名规范
我们知道,不写查询条件就意味着相等条件,那么该规则还有哪些查询条件呢?
我们以下面的表格的形式给出:
关键字 | 方法命名 | 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 > ? |
GreaterThanEqual | findByAgeGreaterThanEqual | where age >= ? |
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(?) |
top | findTop100 | top 10/where ROWNUM <=10 |
标签:SpringData,JPA,方法,入门,查询,规则,where,id,name 来源: https://blog.csdn.net/qq_21046965/article/details/100627603
本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享; 2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关; 3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关; 4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除; 5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。