Springboot-JPA 如何做条件查询

步骤 1 : 可运行项目

首先下载一个简单的可运行项目作为演示:网盘链接https://newryan.lanzous.com/ic2rwad
下载后解压,比如解压到 E:\project\springboot 目录下

步骤 2 : JPA 条件查询方式

JPA 条件查询方式很有意思,是不需要写 SQL 语句的,只需要在 dao 接口里按照规范的命名定义对应的方法名,即可达到查询相应字段的效果了。
在如下代码里做了如下事情:

  1. test1() 查询所有数据
  2. test2() 通过自定义的接口方法 findByName,根据 name 查询分类表
  3. test3() 通过自定义的接口方法 findByNameLikeAndIdGreaterThanOrderByNameAsc,根据名称模糊查询,id 大于某值, 并且名称正排序查询。

TestJPA.java 类:

package com.ryan.springboot.test;
 
import java.util.List;

import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;

import com.ryan.springboot.Application;
import com.ryan.springboot.dao.CategoryDAO;
import com.ryan.springboot.pojo.Category;
 
@RunWith(SpringRunner.class)
@SpringBootTest(classes = Application.class)
public class TestJPA {
 
    @Autowired CategoryDAO dao;   
     
    @Test
    public void test1() {
        List<Category> cs=  dao.findAll();
        System.out.println("所有的分类信息:");
        for (Category c : cs) {
            System.out.println(c.getName());
        }
        System.out.println();
    }
     
    @Test
    public void test2() {
        System.out.println("查询名称是 \" 疯人院\" 的信息:");
        List<Category> cs=  dao.findByName("疯人院");
        for (Category c : cs) {
            System.out.println("c.getName():"+ c.getName());
        }
        System.out.println();
    }
    @Test
    public void test3() {
        System.out.println("根据名称模糊查询,id 大于5, 并且名称正排序查询");
        List<Category> cs=  dao.findByNameLikeAndIdGreaterThanOrderByNameAsc("%人%",5);
        for (Category c : cs) {
            System.out.println(c);
        }
        System.out.println();
         
    }
}

CategoryDAO.java 类:

package com.ryan.springboot.dao;

import java.util.List;

import org.springframework.data.jpa.repository.JpaRepository;

import com.ryan.springboot.pojo.Category;

public interface CategoryDAO extends JpaRepository<Category,Integer>{

	 public List<Category> findByName(String name);
     
	 public List<Category> findByNameLikeAndIdGreaterThanOrderByNameAsc(String name, int id);

}

Category.java 类:

package com.ryan.springboot.pojo;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;

@Entity
@Table(name = "category_")
public class Category {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY) 
    @Column(name = "id") 
	private int id;
    
    @Column(name = "name")
	private String name;
    
	public int getId() {
		return id;
	}
	public void setId(int id) {
		this.id = id;
	}
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	
	@Override
	public String toString() {
		return "Category [id=" + id + ", name=" + name + "]";
	}
	
}

步骤 3 : 实现原理

虽然 JPA 没有自己手动写 sql 语句,但是通过反射获取自定义的接口方法里提供的信息,就知道用户希望根据什么条件来查询了。 然后 JPA 底层再偷偷摸摸地拼装对应的 sql 语句,丢给数据库,就达到了条件查询的效果啦。

对反射不熟悉的同学,可了解反射基础教程: 反射基础教程

步骤 4 : 条件查询规范

上面只是个别举例,下表把 jpa 做的各种查询规范都列出来了。 如果要做其他相关查询,按照表格中的规范设计接口方法即可。

关键词 举例 生成的JPQL 语句片段
And findByLastnameAndFirstname … where x.lastname = ?1 and x.firstname = ?2
Or findByLastnameOrFirstname … where x.lastname = ?1 or x.firstname = ?2
Is,Equals findByFirstname
findByFirstnameIs
findByFirstnameEquals
… where x.firstname = ?1
Between findByStartDateBetween … where x.startDate between ?1 and ?2
LessThan findByAgeLessThan … where x.age < ?1
LessThanEqual findByAgeLessThanEqual … where x.age ⇐ ?1
GreaterThan findByAgeGreaterThan … where x.age > ?1
GreaterThanEqual findByAgeGreaterThanEqual … where x.age >= ?1
After findByStartDateAfter … where x.startDate > ?1
Before findByStartDateBefore … where x.startDate < ?1
IsNull findByAgeIsNull … where x.age is null
IsNotNull,NotNull findByAge(Is)NotNull … where x.age not null
Like findByFirstnameLike … where x.firstname like ?1
NotLike findByFirstnameNotLike … where x.firstname not like ?1
StartingWith findByFirstnameStartingWith … where x.firstname like ?1 (parameter bound with appended %)
EndingWith findByFirstnameEndingWith … where x.firstname like ?1 (parameter bound with prepended %)
Containing findByFirstnameContaining … where x.firstname like ?1 (parameter bound wrapped in %)
OrderBy findByAgeOrderByLastnameDesc … where x.age = ?1 order by x.lastname desc
Not findByLastnameNot … where x.lastname <> ?1
In findByAgeIn(Collection ages) … where x.age in ?1
NotIn findByAgeNotIn(Collection age) … where x.age not in ?1
True findByActiveTrue() … where x.active = true
False findByActiveFalse() … where x.active = false
IgnoreCase findByFirstnameIgnoreCase … where UPPER(x.firstame) = UPPER(?1)

步骤 5 : 测试

运行 TestJPA 类就可以看到如图所示的效果了

更多关于 Springboot_JPA_条件查询 详细内容,点击学习: https://how2j.cn/k/springboot/springboot-jpa-query/1990.html?p=139689

猜你喜欢

转载自www.cnblogs.com/newRyan/p/12803401.html
今日推荐