【问题标题】:spring-data query弹簧数据查询
【发布时间】:2012-08-03 04:34:05
【问题描述】:
public interface AreaRepository extends JpaRepository<Area, Integer>, JpaSpecificationExecutor<Area>{

    @Query("from Area where sup is null")
    List<Area> findProvinces();

    @Query("from Area where sup is null")
    Page<Area> findProvinces(Pageable pg);
}    

这是我的代码。第一种方法工作正常,但第二种方法不行。谁能告诉我如何使它正确?

【问题讨论】:

  • 不,因为您必须更具体地了解“不起作用”的含义。顺便提一句。 @Repository 在这种情况下已过时。
  • 一个不相关的问题,如何使用颜色语法制作我的代码,我看到其他代码的颜色像红色或其他颜色,但我所有的代码都是黑色的,

标签: hql paging spring-data spring-data-jpa


【解决方案1】:

这里不起作用意味着第二个查询抛出错误,无法找出我的sql指定的所有数据

@Query("来自 sup 为空的区域") .

其实我想要归档的是一个使用jpa的qbe模式,我终于得到了一个实现org.springframework.data.jpa.domain.Specification接口的解决方案。

public class QbeSpec<T> implements Specification<T> {

private final T example;

public QbeSpec(T example) {
    this.example = example;
}

@Override
public Predicate toPredicate(Root<T> root, CriteriaQuery<?> query, CriteriaBuilder cb) {
    if (example == null) {
        return cb.isTrue(cb.literal(true));
    }

    BeanInfo info = null;
    try {
        info = Introspector.getBeanInfo(example.getClass());
    } catch (IntrospectionException e) {
        throw new RuntimeException(e);
    }

    List<Predicate> predicates = new ArrayList<Predicate>();
    for (PropertyDescriptor pd : info.getPropertyDescriptors()) {
        String name = pd.getName();
        Object value = null;

        if (name.equals("class"))
            continue;

        try {
            value = pd.getReadMethod().invoke(example);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }

        if (value != null) {
            Path<String> path = root.get(name);
            // string using like others using equal
            if (pd.getPropertyType().equals(String.class)) {
                predicates.add(cb.like(path, "%" + value.toString() + "%"));
            } else {
                predicates.add(cb.equal(path, value));
            }
        }
    }

    return cb.and(predicates.toArray(new Predicate[predicates.size()]));
}

}

【讨论】:

    猜你喜欢
    • 2019-03-13
    • 1970-01-01
    • 2012-08-17
    • 2017-05-21
    • 2019-06-09
    • 2016-10-17
    • 1970-01-01
    • 2019-05-03
    相关资源
    最近更新 更多