0

Suppose I have a table users with attributes id, first_name, last_name, username, email, phone, status(ACTIVE or DELETED defined by enum).

And key being a parameter I want to search in the table.

Here is my service

public void userService(String key){
    UserRepository userRepository ;
    List<Users> userList = userRepository.findByStatusNotAndFirstName
        ContainingOrLastNameContainingOrEmailContainingOrPhoneContaining
        (Status.DELETED, key, key, key, key);
}

Here is my repository

public interface UserRepository extends JpaRepository<User, Long> {
    List<Users> findByStatusNotAndFirstNameContainingOrLastNameContainingOr
    EmailContainingOrPhoneContaining(Status deleted, String key, String key, 
    String key, String key);
}

Is this the proper way of using And and Or in the query?

  • What is `findByStatusNotAndFirstNameContainingOrLastNameContainingOr` suppose to find? I mean, what are the conditions? – lealceldeiro Aug 07 '18 at 20:38
  • It is supposed to find the users whose status is not deleted(i.e. those who are active) and the key to search should be containing either in first_name or last_name or email or phone. – Sujan Limbu Aug 08 '18 at 09:46
  • This syntax is incorrect: `List userList = userRepository.findByStatusNotAndFirstNameContainingOrLastNameContainingOrEmailContainingOrPhoneContaining(Status.DELETED, String key, String key, String key, String key);` When you call a method you don't define the type of the arguments; that's in the method signature. – lealceldeiro Aug 08 '18 at 11:46
  • Please consider to provide a [Minimal, Complete, and Verifiable example](http://stackoverflow.com/help/mcve) if possible. This way, it's more likely volunteers on SO can help you. The code you provided shouldn't even compile. – lealceldeiro Aug 08 '18 at 11:46
  • hope my edited code works. – Sujan Limbu Aug 09 '18 at 08:47

1 Answers1

1

First of all, you should create integration test with memory database for your repository class. So you can try if the query returns the correct result.

Even if you can define multiple "or" and "and" operators in the method name, it will be a mess to read and understand. I recommend creating a method with readable name and using the org.springframework.data.jpa.repository.Query annotation to define the JPA query.

vargapeti
  • 301
  • 2
  • 7