Spring Data JPA 实例查询

一、相关接口方法

在继承JpaRepository接口后,自动拥有了按“实例”进行查询的诸多方法。这些方法主要在两个接口中定义,一是QueryByExampleExecutor,一个是JpaRepository,如下所示:

public interface QueryByExampleExecutor<T> { 
	<S extends T> S findOne(Example<S> example); //根据“实例”查找一个对象。
	<S extends T> Iterable<S> findAll(Example<S> example); //根据“实例”查找一批对象
	<S extends T> Iterable<S> findAll(Example<S> example, Sort sort); //根据“实例”查找一批对象,且排序
	<S extends T> Page<S> findAll(Example<S> example, Pageable pageable); //根据“实例”查找一批对象,且排序和分页
	<S extends T> long count(Example<S> example); //根据“实例”查找,返回符合条件的对象个数
	<S extends T> boolean exists(Example<S> example); //根据“实例”判断是否有符合条件的对象
}
@NoRepositoryBean public interface JpaRepository<T, ID extends Serializable> 
  extends PagingAndSortingRepository<T, ID>, QueryByExampleExecutor<T> {
 	...... 
	@Override 
	<S extends T> List<S> findAll(Example<S> example); //根据实例查询 
	@Override 
	<S extends T> List<S> findAll(Example<S> example, Sort sort);//根据实例查询,并排序。 
}

二、快速入门

观察上面的方法,其参数都有一个 Example 类对象,这就一个“实例”(个人翻译的叫法,未必准确),它代表的是查询条件,它是通过包装要查询的实体对象而生成的。下面通过一个例子,来快速了解一下其用法。

1、定义实体类

如有 客户信息、客户类型 两个实体类定义如下:

/**
* 客户
*/
@Entity
@Table(name = "demo_lx_Customer")
public class Customer extends BaseBo
{
  private String name; //姓名
  private String sex; //性别
  private int age; //年龄
  private String address; //地址
  private boolean focus ; //是否重点关注
  private Date addTime; //创建时间
  private String remark; //备注
  @ManyToOne
  private CustomerType customerType; //客户类型
  ......
}
/**
* 客户类型
*/
@Entity
@Table(name = "demo_lx_CustomerType")
public class CustomerType extends BaseBo
{ 
  private String code; //编号
  private String name; //名称
  private String remark; //备注
  ......
}
2、模拟数据

在这里插入图片描述

3、查询

现在要查询:地址是“郑州市”,姓“刘”的客户,可以这样来写:

//创建查询条件数据对象
        Customer customer = new Customer();
        customer.setName("刘");
        customer.setAddress("河南省郑州市");

        //创建匹配器,即如何使用查询条件
        ExampleMatcher matcher = ExampleMatcher.matching() //构建对象
                .withMatcher("name", GenericPropertyMatchers.startsWith()) //姓名采用“开始匹配”的方式查询
                .withIgnorePaths("focus");  //忽略属性:是否关注。因为是基本类型,需要忽略掉
        
        //创建实例
        Example<Customer> ex = Example.of(customer, matcher); 
        
        //查询
        List<Customer> ls = dao.findAll(ex);
        
        //输出结果
        System.out.println("数量:"+ls.size());
        for (Customer bo:ls)
        {
            System.out.println(bo.getName());
        }

输出结果:

数量:1
刘芳

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值