【问题标题】:Criteria in spring data春季数据中的标准
【发布时间】:2015-06-01 13:30:29
【问题描述】:

我正在使用 angular js、spring mvc 和 spring jpa 数据开发一个 Web 应用程序。 我想知道是否有类似于标准和分离标准(休眠)的东西来使用spring jpa数据构建高级查询。

【问题讨论】:

标签: spring hibernate spring-data


【解决方案1】:

没有什么能阻止您仍然使用 Criteria

@Repository
public interface FooRepository extends JpaRepository<Foo, Long>, FooRepositoryCustom {

}

interface FooRepositoryCustom {

    public List<Foo> findByBar(Bar bar);
}

class FooRepositoryImpl implements FooRepositoryCustom {

    @PersistenceContext
    protected EntityManager em;

    @Transactional(readOnly = true)
    public List<Foo> findByBar(Bar bar) {

        Criteria crit = em.unwrap(Session.class).createCriteria(Foo.class);

        crit.add(Restrictions.eq("name", bar.getName()));

        ...

        crit.setResultTransformer(DetachedCriteria.DISTINCT_ROOT_ENTITY);

        List<Foo> foos = crit.list();

        return foos;

    }
}

【讨论】:

    【解决方案2】:

    是的,您可以使用Specifications,它基本上使用 Criteria API(显然,因为 Spring Data JPA 只是 JPA 的包装器)。

    【讨论】:

    • 保存引用其他 2 个对象的对象的最佳方法是什么?如何只用一个查询来做到这一点。 (无需从数据库中检索它们)。
    • 您应该将此作为一个新问题提出(如果对第一个问题有帮助,请接受我的回答)。
    • 另外你应该阅读stackoverflow.com/help,尤其是“询问”部分。
    【解决方案3】:

    您可以使用Query Dsl ,它比Specification 更简洁,这里是一个包含SpecificationQueryDslblog

    【讨论】:

      【解决方案4】:

      您可以将 Criteria 与 Spring Data 一起使用,您不需要自定义存储库,您可以使用 JpaSpecificationExecutor,这里是一个示例:

      您的存储库:

      @Repository("yourRepository")
      public interface YourRepository extends JpaRepository, JpaSpecificationExecutor
      {
      }
      

      您的服务

      @Override
      public List<YourModel> yourDataModel getAllEntitiesByAttr(String attrValue){
          List<YourModel> yourDataModel = null;
          try {
           Specification specification=getAndSpecByAttribute("attribute",attrValue);
           List list = userRepository.findAll(specification);
           yourDataModel =orikaMapper.mapAsList(list, YourModel.class);
          } catch (Exception e) {
           throw e;
          }
          return yourDataModel;
      }
      private Specification getAndSpecByAttribute(String attribute, String valueAttribute){
       return new Specification() {
            @Override public Predicate toPredicate(Root root, CriteriaQuery query, CriteriaBuilder cb) {
              Path path = root.get(attribute);
             return cb.equal(path, valueAttribute);
            };
          };
      }
      

      够了。

      【讨论】:

        猜你喜欢
        • 2016-01-30
        • 2016-03-27
        • 1970-01-01
        • 2014-08-03
        • 2013-03-23
        • 2013-11-12
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多