0
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);
}    

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

4

1 回答 1

1

here doesn't work mean the second query throws an error and can't find out all the data specified by my sql

@Query("from Area where sup is null") .

Actually what i want to archieve is a qbe pattern using jpa,and i finally got a solution implementing org.springframework.data.jpa.domain.Specification interface.

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()]));
}

}

于 2012-08-07T01:27:05.547 回答