自定义Repository访问数据库
- JPA 除了可以直接调用相关接口来访问和操作数据库,还支持通过继承接口自定义 Repository 实现访问数据库,自定义实现主要工作为自定义编辑一个 Specification,一个继承 JpaRepository 的 Interface 以及相应的实现,定义一个 repositoryFactoryBean。
1、Specification 自定义
- 在项目目录下新建一个 specs 文件夹,新建一个 CustomSpecs 类,编辑如下代码:
package com.pyc.springjpa.specs; import static com.google.common.collect.Iterables.toArray; import org.springframework.data.jpa.domain.Specification; import org.springframework.util.ReflectionUtils; import org.springframework.util.StringUtils; import javax.persistence.EntityManager; import javax.persistence.criteria.CriteriaBuilder; import javax.persistence.criteria.CriteriaQuery; import javax.persistence.criteria.Predicate; import javax.persistence.criteria.Root; import javax.persistence.metamodel.Attribute; import javax.persistence.metamodel.EntityType; import javax.persistence.metamodel.SingularAttribute; import java.lang.reflect.Field; import java.util.ArrayList; import java.util.List; public class CustomSpecs { // Define a method that returns a Specification and named byAuto, use generic as return type of this method // so that this method can affect any entity class,the parameter of this method is entityManager // and a query condition with current parameter value. // 定义一个返回值为 Specification 名称为byAuto的方法,使用泛型 T,表明这个Specification 可用于 // 任何实体类;参数为 entityManager 和包含当前值的查询条件 public static <T> Specification<T> byAuto(final EntityManager entityManager, final T example) { //获得当前实体类对象的类型 final Class<T> type = (Class<T>) example.getClass(); return new Specification<T>() { @Override public Predicate toPredicate(Root<T> root, CriteriaQuery<?> criteriaQuery, CriteriaBuilder criteriaBuilder) { // create a Predicate list to stores the constructed query conditions List<Predicate> predicates = new ArrayList<>(); //新建 Predicate 列表存储构造的查询条件 // get the type of entity so,and then can get the attributes of entity by using entity type //获得实体类的 EntityType,从而获得实体类的属性 EntityType<T> entity = entityManager.getMetamodel().entity(type); // Doing loop on all attributes of entity // 对实体类的所有属性做循环 for (Attribute<T, ?> attr : entity.getDeclaredAttributes(