2012-08-06 98 views
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); 
}  

這是我的代碼。第一種方法工作正常,但第二種方法沒有。任何人都可以告訴我如何使其正確?彈簧數據查詢

+1

不,你一定要具體談談什麼是「不工作」的意思。順便說一句。在這種情況下,「@ Repository」已經過時。 – 2012-08-06 16:18:35

+0

一個無關的問題,如何使我的代碼與顏色語法,我看到別人的代碼是紅色或其他顏色,但我所有的代碼是黑色的, – johnicesea 2012-08-07 01:29:16

回答

1

這裏不起作用意味着第二個查詢拋出一個錯誤,無法找到我的SQL

@Query(「從景區裏SUP爲空」) 指定的所有數據。

其實我想archieve什麼是使用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()])); 
} 

}