FlyingTurtle
FlyingTurtle

Reputation: 155

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

I trying to make query in JPA without repetition condition and variable:

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.

Upvotes: 0

Views: 1312

Answers (1)

Naros
Naros

Reputation: 21113

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:

@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.

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

Upvotes: 1

Related Questions