如何在Spring Data Jpa中编写一个接受四种参数组合的select查询

时间:2017-06-22 15:49:01

标签: java sql spring spring-data-jpa

我试图在用户搜索多个组合时显示结果,他可以搜索的选项 -

  
      
  1. 国家
  2.   
  3.   
  4.   
  5. 邮政编码
  6.   

他可以搜索的示例组合是(国家,州),(国家,地区),(州,zipCode)等。

我正在使用Spring Data Jpa进行查询和分页。

我是Spring Jpa的新手,任何帮助都将不胜感激。

谢谢!

3 个答案:

答案 0 :(得分:1)

有一个非常简单的技巧可以执行你需要的东西;)

@Query("select e from Entity e where "
      +"(:country = '' or e.country like '%:country%') and "
      +"(:state = '' or e.state like '%:state%') and "
      +"(:district = '' or e.district like '%:district%') and "
      +"(:zipCode = '' or e.zipCode like '%:zipCode%')"
Page<Entity> advancedSearch(@Param("country") String country,
                            @Param("state") String state,
                            @Param("district") String district,
                            @Param("zipCode") String zipCode,
                            Pageable page);

因此,当您需要调用advancedSearch时,您可以只设置您需要的参数,将其他参数设置为""

Page<Entity> enityPages = advancedSearch("", "California", "1st", "", new PageRequest(...)); 

答案 1 :(得分:0)

使用标准:

public Collection<? extends Profile> get(Collection<? extends Integer> ids, boolean deleted) {
    CriteriaBuilder cb = em.getCriteriaBuilder();
    CriteriaQuery<Profile> q = cb.createQuery(Profile.class);
    Root<Profile> r = q.from(Profile.class);

    if (deleted) {
        Predicate andClose = cb.and(cb.equal(r.get("deleted"), true));
        q.where(r.get("id").in(ids), andClose);
    } else {
        q.where(r.get("id").in(ids));
    }            

    q.orderBy(cb.asc(r.get("id")));

    TypedQuery<Profile> query = em.createQuery(q);

    return query.getResultList();
}

顺便说一句,您可以自由添加一些if (... )来使用或不使用某些Predicate,具体取决于get的传入参数

答案 2 :(得分:0)

如果您正在扩展JpaRepository接口并让Spring Data处理查询的连接和自动生成,您可以轻松扩展接口以处理您的方案,而无需编写任何过于复杂的内容:

public interface CustomerRepository extends JpaRepository<Customer, Integer> {
    public List<Customer> findAllByCountryAndState(String country, String State);

}

您可以按如下方式使用此方法:

@Autowired
private CustomerRepository customerRepository;

public void testMethod(){
    List<Customer> customerList = customerRepository.findAllByCountryAndState("Canada","Ontario");
}

Spring文档有很多例子:Spring Data Query Creation