SpringData入门(四)SpringData JPA之方法名称规则查询

前言

     本章讲解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字句
AndfindByNameAndPwdwhere name= ? and pwd =?
OrfindByNameOrSexwhere name= ? or sex=?
Is,EqualsfindById,findByIdEqualswhere id= ?
BetweenfindByIdBetweenwhere id between ? and ?
LessThanfindByIdLessThanwhere id < ?
LessThanEqualsfindByIdLessThanEqualswhere id <= ?
GreaterThanfindByIdGreaterThanwhere id > ?
GreaterThanEqualfindByAgeGreaterThanEqualwhere age >= ?
AfterfindByIdAfterwhere id > ?
BeforefindByIdBeforewhere id < ?
IsNullfindByNameIsNullwhere name is null
isNotNull,NotNullfindByNameNotNullwhere name is not null
LikefindByNameLikewhere name like ?
NotLikefindByNameNotLikewhere name not like ?
StartingWithfindByNameStartingWithwhere name like '?%'
EndingWithfindByNameEndingWithwhere name like '%?'
ContainingfindByNameContainingwhere name like '%?%'
OrderByfindByIdOrderByXDescwhere id=? order by x desc
NotfindByNameNotwhere name <> ?
InfindByIdIn(Collection<?> c)where id in (?)
NotInfindByIdNotIn(Collection<?> c)where id not  in (?)
TRUEfindByAaaTuewhere aaa = true
FALSEfindByAaaFalsewhere aaa = false
IgnoreCasefindByNameIgnoreCasewhere UPPER(name)=UPPER(?)
topfindTop100top 10/where ROWNUM <=10
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值