简体   繁体   English

如何以正确的方式使查询Spring数据JPA多条件?

[英]How to make query Spring data JPA multi condition with proper way?

I trying to make query in JPA without repetition condition and variable: 我试图在JPA中进行查询,而没有重复条件和变量:

List<User> findByNameContainingIgnoreCaseAndEnabledOrUsernameContainingIgnoreCaseAndEnabledOrEmailContainingIgnoreCaseAndEnabledOrAgency_NameContainingIgnoreCaseAndEnabled
(String name, boolean status1, String username,boolean status2, String email, boolean status3,String agencyName, boolean status, Pageable pageable);

Im not sure whether my way proper or not. 我不确定我的方式是否正确。 But is so hard to read. 但是很难读。

The best way to accomplish this is not to use the method expansion approach for spring-data to construct the actual query but to instead make use of the @Query annotation in this case: 实现此目的的最佳方法不是在spring-data中使用方法扩展方法来构造实际查询,而是在这种情况下使用@Query注释:

@Query(value = "SELECT ...")
List<User> findUsersByParams(
  @Param("name") String name,
  @Param("status1") boolean status1,
  @Param("username") String username,
  @Param("status2") boolean status2, 
  @Param("email") String email, 
  @Param("status3") boolean status3,
  @Param("agencyname") String agencyName, 
  @Param("status") boolean status, 
  Pageable pageable);

The key here is that the value attribute in the @Query annotation takes a JPQL query that defines a series of named parameters and each of the @Param annotated method values are matched to those query named parameters and injected for you automatically. 这里的关键是@Query批注中的value属性采用一个JPQL查询,该查询定义了一系列命名参数,并且每个@Param注释的方法值都与那些查询命名参数匹配并自动为您注入。

A trivial example is 一个简单的例子是

@Query(value = "SELECT u FROM User u " +
       "WHERE u.userName LIKE CONCAT('%', :userName, '%')")
List<User> findUsersByParams(@Param("userName") String userName, Pageable page);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM