【问题标题】:Spring Data JPA + JpaSpecificationExecutor + EntityGraphSpring Data JPA + JpaSpecificationExecutor + EntityGraph
【发布时间】:2014-12-05 03:13:57
【问题描述】:

(使用 Spring Data JPA)我有两个实体 Parent& Child,它们之间具有 OneToMany/ManyToOne 双向关系。我将@NamedEntityGraph 添加到父实体,如下所示:

@Entity
@NamedEntityGraph(name = "Parent.Offspring", attributeNodes = @NamedAttributeNodes("children"))
public class Parent{
//blah blah blah

@OneToMany(mappedBy = "parent", fetch = FetchType.LAZY)
Set<Child> children;

//blah blah blah
}

请注意,Parent 的孩子的获取类型是 LAZY。这是故意的。当我查询单个父母时,我并不总是想急切地加载孩子。通常我可以使用我的命名实体图来按需加载孩子,可以这么说。但是.....

在一种特定情况下,我想查询一位或多位父母并急切地加载他们的孩子。除此之外,我需要能够以编程方式构建此查询。 Spring Data 提供了JpaSpecificationExecutor,它允许构建动态查询,但我不知道如何将它与实体图结合使用,以便在这种特定情况下急切加载子项。这甚至可能吗?是否有其他方法可以使用规范急切加载“toMany 实体”?

【问题讨论】:

  • 你找到这个问题的答案了吗?

标签: java spring jpa spring-data spring-data-jpa


【解决方案1】:

解决方案是创建实现这些功能的自定义存储库接口:

@NoRepositoryBean
public interface CustomRepository<T, ID extends Serializable> extends JpaRepository<T, ID>, JpaSpecificationExecutor<T> {

    List<T> findAll(Specification<T> spec, EntityGraphType entityGraphType, String entityGraphName);
    Page<T> findAll(Specification<T> spec, Pageable pageable, EntityGraphType entityGraphType, String entityGraphName);
    List<T> findAll(Specification<T> spec, Sort sort, EntityGraphType entityGraphType, String entityGraphName);
    T findOne(Specification<T> spec, EntityGraphType entityGraphType, String entityGraphName);

}

同时创建一个实现:

@NoRepositoryBean
public class CustomRepositoryImpl<T, ID extends Serializable> extends SimpleJpaRepository<T, ID> implements CustomRepository<T, ID> {

    private EntityManager em;

    public CustomRepositoryImpl(Class<T> domainClass, EntityManager em) {
        super(domainClass, em);
        this.em = em;
    }

    @Override
    public List<T> findAll(Specification<T> spec, EntityGraph.EntityGraphType entityGraphType, String entityGraphName) {
        TypedQuery<T> query = getQuery(spec, (Sort) null);
        query.setHint(entityGraphType.getKey(), em.getEntityGraph(entityGraphName));
        return query.getResultList();
    }

    @Override
    public Page<T> findAll(Specification<T> spec, Pageable pageable, EntityGraph.EntityGraphType entityGraphType, String entityGraphName) {
        TypedQuery<T> query = getQuery(spec, pageable.getSort());
        query.setHint(entityGraphType.getKey(), em.getEntityGraph(entityGraphName));
        return readPage(query, pageable, spec);
    }

    @Override
    public List<T> findAll(Specification<T> spec, Sort sort, EntityGraph.EntityGraphType entityGraphType, String entityGraphName) {
        TypedQuery<T> query = getQuery(spec, sort);
        query.setHint(entityGraphType.getKey(), em.getEntityGraph(entityGraphName));
        return query.getResultList();
    }

    @Override
    public T findOne(Specification<T> spec, EntityGraph.EntityGraphType entityGraphType, String entityGraphName) {
        TypedQuery<T> query = getQuery(spec, (Sort) null);
        query.setHint(entityGraphType.getKey(), em.getEntityGraph(entityGraphName));
        return query.getSingleResult();
    }
}

并创建一个工厂:

public class CustomRepositoryFactoryBean<R extends JpaRepository<T, I>, T, I extends Serializable> extends JpaRepositoryFactoryBean<R, T, I> {

    protected RepositoryFactorySupport createRepositoryFactory(EntityManager entityManager) {
        return new CustomRepositoryFactory(entityManager);
    }

    private static class CustomRepositoryFactory<T, I extends Serializable> extends JpaRepositoryFactory {

        private EntityManager entityManager;

        public CustomRepositoryFactory(EntityManager entityManager) {
            super(entityManager);
            this.entityManager = entityManager;
        }

        protected Object getTargetRepository(RepositoryMetadata metadata) {
            return new CustomRepositoryImpl<T, I>((Class<T>) metadata.getDomainType(), entityManager);
        }

        protected Class<?> getRepositoryBaseClass(RepositoryMetadata metadata) {
            // The RepositoryMetadata can be safely ignored, it is used by the JpaRepositoryFactory
            //to check for QueryDslJpaRepository's which is out of scope.
            return CustomRepository.class;
        }
    }

}

并将默认存储库工厂 bean 更改为新 bean,例如在 Spring Boot 中将其添加到配置中:

@EnableJpaRepositories(
    basePackages = {"your.package"},
    repositoryFactoryBeanClass = CustomRepositoryFactoryBean.class
)

有关自定义存储库的更多信息:http://docs.spring.io/spring-data/jpa/docs/current/reference/html/#repositories.custom-behaviour-for-all-repositories

【讨论】:

  • 出色的工作@Joepie,为我节省了几个小时的工作时间。
  • readPage(javax.persistence.TypedQuery&lt;T&gt; query, Pageable pageable, @Nullable Specification&lt;T&gt; spec) 现在不推荐使用readPage(TypedQuery, Class, Pageable, Specification)。
  • 在 Spring Data JPA 的最新版本中(从 2.0 开始的版本),而不是 (Sort) null 使用 Sort.unsorted()
【解决方案2】:

Joepie 的反应还可以。

但不需要创建repositoryFactoryBeanClass,设置repositoryBaseClass

@EnableJpaRepositories(
    basePackages = {"your.package"},
    repositoryBaseClass = CustomRepositoryImpl.class)

【讨论】:

    【解决方案3】:

    为了补充Joep和pbo的答案,我不得不说,使用新版本的Spring Data JPA,你将不得不修改CustomRepositoryImpl的构造函数。现在documentation 说:

    该类需要具有特定于商店的存储库工厂实现正在使用的超类的构造函数。如果存储库基类有多个构造函数,请覆盖采用 EntityInformation 和存储特定基础架构对象(例如 EntityManager 或模板类)的构造函数。

    我使用以下构造函数:

    public CustomRepositoryImpl(JpaEntityInformation<T,?> entityInformation, EntityManager em) {
        super(entityInformation, em);
        this.domainClass = entityInformation.getJavaType();
        this.em = em;
    }
    

    我还添加了一个私有字段来存储域类:

    private final Class<T> domainClass;
    

    这让我可以摆脱不推荐使用的方法readPage(javax.persistence.TypedQuery&lt;T&gt; query, Pageable pageable, @Nullable Specification&lt;T&gt; spec) 并改用:

    @Override
    public Page<T> findAll(Specification<T> spec, Pageable pageable, EntityGraph.EntityGraphType entityGraphType, String entityGraphName) {
        TypedQuery<T> query = getQuery(spec, pageable.getSort());
        query.setHint(entityGraphType.getKey(), em.getEntityGraph(entityGraphName));
        return readPage(query, domainClass, pageable, spec);
     }
    

    【讨论】:

    【解决方案4】:

    Project Spring Data JPA EntityGraph 实现了其他答案中提到的一些方法。

    它具有例如这些额外的存储库接口:

    • EntityGraphJpaRepository 相当于标准的JpaRepository
    • EntityGraphJpaSpecificationExecutor 相当于标准的JpaSpecificationExecutor

    查看reference documentation 获取一些示例。

    【讨论】:

      【解决方案5】:

      我设法通过覆盖findAll 方法并添加注释@EntityGraph 来实现这一点:

      public interface BookRepository extends JpaSpecificationExecutor<Book> {
         @Override
         @EntityGraph(attributePaths = {"book.author"})
         List<Book> findAll(Specification<Book> spec);
      }
      

      【讨论】:

      • 非常优雅的解决方案。谢谢:-)
      • @vteraz 我无法使用在实体上声明的 NamedEntityGraph 来处理覆盖的 JpaRepository findById。和上面的例子有什么区别?声明一个新方法 findWithAttributesAll 将尊重 NamedEntityGraph。
      • 即使使用@NamedEntityGraph,它也适用于我。您可以发布您的案例示例吗?
      • 有没有办法使用这个解决方案来加载多个 OneToMany 关联?
      【解决方案6】:

      顺便说一句,存储库bean的工厂不是必需的。你只需要一个简单的 Bean。

      您可以在此处查看我的完整示例:https://github.com/netstart/POCs/tree/master/jpa/jpaspecification-whith-entity-graph

      
      import com.specgraph.entitygraph.model.Characteristic;
      import org.springframework.data.domain.Page;
      import org.springframework.data.domain.Pageable;
      import org.springframework.data.jpa.domain.Specification;
      import org.springframework.data.jpa.repository.EntityGraph;
      import org.springframework.data.jpa.repository.EntityGraph.EntityGraphType;
      import org.springframework.data.jpa.repository.support.SimpleJpaRepository;
      import org.springframework.data.repository.NoRepositoryBean;
      
      import javax.persistence.EntityManager;
      import javax.persistence.TypedQuery;
      
      @NoRepositoryBean
      public class CharacteristicsJpaSpecificationRepository extends SimpleJpaRepository<Characteristic, Long> {
      
         private final EntityManager em;
      
         public CharacteristicsJpaSpecificationRepository(Class<Characteristic> domainClass, EntityManager em) {
             super(domainClass, em);
             this.em = em;
         }
      
         public Page<Characteristic> findByTypeUsingSpecification(String type, Pageable pageable) {
             Specification<Characteristic> spec =
                 (root, query, criteriaBuilder) -> criteriaBuilder.equal(root.get("type"), type);
      
             return findAll(spec, pageable, EntityGraphType.FETCH, "Characteristic.item");
         }
      
         public Page<Characteristic> findAll(Specification<Characteristic> spec,
                                             Pageable pageable,
                                             EntityGraph.EntityGraphType entityGraphType,
                                             String entityGraphName) {
      
             TypedQuery<Characteristic> query = getQuery(spec, pageable.getSort());
             query.setHint(entityGraphType.getKey(), em.getEntityGraph(entityGraphName));
             return readPage(query, Characteristic.class, pageable, spec);
         }
      
      }
      
      
      import com.specgraph.entitygraph.model.Characteristic;
      import org.springframework.context.annotation.Bean;
      import org.springframework.context.annotation.Configuration;
      
      import javax.persistence.EntityManager;
      import javax.persistence.PersistenceContext;
      
      @Configuration
      public class MyRepositoryConfiguration {
      
          @PersistenceContext // this will inject em in your class
          private EntityManager em;
      
          @Bean
          public CharacteristicsJpaSpecificationRepository getCharacteristicsJpaSpecificationRepository() {
              return new CharacteristicsJpaSpecificationRepository(Characteristic.class, em);
          }
      
      }
      
      
      import com.specgraph.entitygraph.model.Characteristic;
      import com.specgraph.entitygraph.repository.specentitygraph.CharacteristicsJpaSpecificationRepository;
      import org.junit.jupiter.api.Test;
      import org.springframework.beans.factory.annotation.Autowired;
      import org.springframework.boot.test.autoconfigure.orm.jpa.DataJpaTest;
      import org.springframework.data.domain.Page;
      import org.springframework.data.domain.PageRequest;
      import org.springframework.test.context.jdbc.Sql;
      
      import static org.assertj.core.api.Assertions.assertThat;
      
      @DataJpaTest
      @Sql(scripts = "/entitygraph-data.sql")
      public class CharacteristicsJpaSpecificationTest2 {
      
          @Autowired
          private CharacteristicsJpaSpecificationRepository characteristicsJpaSpecificationRepository;
      
          @Test
          public void find() {
              int pageNumber = 1;
              int pageSize = 10;
              PageRequest pageable = PageRequest.of(pageNumber, pageSize);
      
              Page<Characteristic> page =
                  characteristicsJpaSpecificationRepository.findByTypeUsingSpecification("Rigid", pageable);
      
              assertThat(page.getTotalElements()).isEqualTo(1);
          }
      
      }
      

      【讨论】:

        【解决方案7】:

        看看Composite Specification API,它可以满足您的需求。 This 类实现了Specification 接口,并且可以像example 那样组成。 在您获取姓氏“Doe”的父母及其 1990 年 1 月 1 日之前出生的孩子的情况下,您需要以下说明:

        public final class ParentSpecifications {
        
            private ParentSpecifications() {
            }
        
            public static <S extends Path<Parent>> CompositeSpecification<Parent, S> surname(String surname) {
                return CompositeSpecification.<Parent, S, TypeSafePredicateBuilder<Path<Parent>>>of(
                        (root, query, criteriaBuilder) -> criteriaBuilder.equal(root.get("surname"), surname)
                );
            }
        
            public static <S extends From<?, Parent>> CompositeSpecification<Parent, S> fetchChildren(CompositeSpecification<?, ? super Join<?, Child>> childSpecification) {
                return CompositeSpecification.<Parent, S, TypeSafePredicateBuilder<From<?, Parent>>>of(
                        (root, query, criteriaBuilder) -> {
                            query.distinct(true);
                            return childSpecification.asBuilder().toPredicate((Join<Parent, Child>) root.<Parent, Child>fetch("children", JoinType.LEFT), query, criteriaBuilder);
                        });
            }
        }
        
        public final class ChildSpecifications {
        
            private ChildSpecifications() {
            }
            
            public static <S extends Path<Child>> CompositeSpecification<Child, S> dateOfBirth(CompositeSpecification<?, ? super Path<LocalDate>> dateOfBirthSpecification) {
                return CompositeSpecification.<Child, S, TypeSafePredicateBuilder<Path<Child>>>of(
                        (root, query, criteriaBuilder) -> dateOfBirthSpecification.asBuilder().toPredicate(root.get("dateOfBirth"), query, criteriaBuilder)
                );
            }
        }
        

        和查询:

        var parents = parentRepository.findAll(surname("Doe").and(fetchChildren(dateOfBirth(lessThan(LocalDate.of(1990,1,1))))));
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2020-08-18
          • 2018-11-29
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2012-07-15
          • 1970-01-01
          • 2015-02-14
          相关资源
          最近更新 更多