Skip to content
On this page

方法命名查询

基本的增删改查都是继承自JpaRepository类的方法,只能满足常规的增删改查,其中查询提供了查全表和根据id查某条记录的方法。

如果像根据其他属性查询表中的数据,则可以使用spring data jpa提供的方法命名查询

方法命名查蓄奴是通过解析方法名来创建满足开发者自身逻辑的查询,其规则以find...by,read...by,query...by,get...by。在进行方法名进行解析时,框架会先把方法名对于的前缀去除,然后对剩下的部分进行解析,其中第一个By会被用作分隔符来指示实际查询条件的开始,再使用实体属性来定义条件,并将他们与And或者Or连接起来,从而创建适用于各种情况的查询

关键字方法命名sql where 语句
AndfindByNameAndPwdwhere name = ? and pwd ?
OrfindByNameOrSexwhere name = ? or sex = ?
Is, EqualsfindById,findByIdEqualswhere id = ?
BetweenfindByIdBetweenwhere id between ? and ?
LessThanfindByIdLessThanwhere id < ?
LessThanEqualsfindByIdLessThanEqualswhere id <= ?
GreaterThanfindByIdGreaterThanwhere id > ?
GreaterThanEqualsfindByIdGreaterThanEqualswhere id >= ?
AfterfindByIdAfterwhere id > ?
BeforefindByIdBeforewhere id < ?
IsNullfindByNameIsNullwhere name is null

利用方法命名查询,可以构建非常复杂、特殊的查询。

如下:

java
package com.huangjiliang.jpa.repository;

import com.huangjiliang.jpa.entity.Employee;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;

import java.util.List;

@Repository
public interface EmployeeRepository extends JpaRepository<Employee, Integer> {
    /**
     * 根据名称和编号进行查询
     * @param name
     * @param userName
     * @return
     */
    List<Employee> findByNameAndUserNumber(String name, Integer userName);

    /**
     * 根据名称模糊查询且年龄在一定的范围
     * @param name
     * @param startAge
     * @param endAge
     * @return
     */
    List<Employee> findByNameContainingAndAgeBetween(String name, Integer startAge, Integer endAge);

}
java
@Test
    public void testCustomSql() {
        List<Employee> list = employeeRepository.findByNameContainingAndAgeBetween("黄继", 9, 11);
        for (Employee employee : list) {
            logger.info(employee.getName());
            logger.info(employee.getDept().getDeptName());
        }
    }