spring-数据查询

问题描述 投票:0回答:1
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);
}    

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

spring-data-jpa pagination spring-data hql
1个回答
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()]));
}

}

© www.soinside.com 2019 - 2024. All rights reserved.