Spring data repositories - parameter what to retrieve all records?

14,162

Solution 1

You should extend your repository from JpaRepository. Be careful with name of repository (It should follow convention). After you inject your UserRepository bean you will have already implemeted by spring data crud methods like findOne(), findAll(), delete() etc.

@Repository
public interface UserRepository extends JpaRepository<User, Long> {
   //assume your primary key is Long type
}

Also will be useful documentation

Solution 2

Have you considered using a spring data specification? In spring data a specification is a way to wrap the JPA criteria api.

The idea behind the JPA Criteria api is to generate queries programatically, by defining query objects.

Once you have encapsulated the criteria in a specification objects, a single findAll method can be used in a number of scenarios. For example programatically add criteria based input form the user, such as additional search filters etc.

To use this feature a repo will need to extend "JpaSpecificationExecutor"

public interface UserRepository extends JpaRepository<User>, JpaSpecificationExecutor {
      List<T> findAll(Specification<T> spec);
}

The find method can then be called with multiple criteria, or the criteria can be built dynamically based on the situation:

List<User> users = userRepository.findAll(where(userLastNameIs("John")).and(userIsArchived())); 

Alternatively you can also try query by exampe. The idea here is to provide the actual domain object with the populated search fields to an example matcher. Configure the example matcher to control the search and pass it to the findAll method.

Again the repo will need to implement an interface. Check the documentation for the detailed pros/cons of each approach.

Person person = new Person();                          
person.setFirstname("Dave");                           

ExampleMatcher matcher = ExampleMatcher.matching()     
  .withIgnorePaths("lastname")                         
  .withIncludeNullValues()                             
  .withStringMatcherEnding();                          

Example<Person> example = Example.of(person, matcher);
List<Person> people = personRepository.findAll(example);

Solution 3

As I got from comments you're trying to achieve ignorance of null values of passed parameters (instead of retrieving all records by findAll()).

Unfortunately, currently, it's not supported by Spring .

You could leverage the @Query annotation and write the query manually in such manner:

@Query("select u from User u where "
    + "(:firstname is null or u.firstname = :firstname)"
    + "(:lastname is null or u.lastname = :lastname)"
)
public List<User> findUserByFirstNameAndLastName(
    @Param("firstname") String firstname, 
    @Param("lastname") String lastname
);
Share:
14,162
TS How
Author by

TS How

Updated on June 18, 2022

Comments

  • TS How
    TS How almost 2 years
    @Repository
    public interface UserDao extends User {
       public List<User> findByFirstname(String firstname);
    }
    

    How could I use above code to retrieve all records? I tried findByFistname(null);, it doesn't work... I don't want to use findByFirstname(); because it's possible to have parameter.

    Hope you all understand.

  • TS How
    TS How over 7 years
    Assume: findByFirstname(String firstname) can work. When use: findByFirstname("DAVID"), it will return all the records which firstname = "DAVID". but what i want is passing in NULL or empty string to return all the records, is it possible to do that? I dont want to use findAll(), because certain time i still need to passing in parameter for specific requirement.
  • jahra
    jahra over 7 years
    Why not use if (StringUtils.isEmpty(param)) {userRepository.findAll()} else {userRepository.findByFirstname(param} @TSHow
  • TS How
    TS How over 7 years
    Because i have multiple columns (6 columns right now) need to filter... if using if else method, then will have 6*5*4*3*2*1 methods if...else if...else if * N ... else
  • jahra
    jahra over 7 years
    Can you post some code to understand what your want to achive? @TSHow
  • TS How
    TS How over 7 years
    it's very simple, user able to search by firstname, lastname, gender and identityId. findByFirstnameAndLastnameAndGenderAndIdentityId(String firstname, String lastname, String gender, String identityId). But certain time, user may only key in firstname and gender.
  • jahra
    jahra over 7 years
    Maybe something like findDistinctByFirstnameOrLastnameOrGenderOrIdentityId(String firstname, String lastname, String gender, String identityId) @TSHow
  • TS How
    TS How over 7 years
    sorry for that i cant share the code, because this is company's asset, if i share to other people, company will sue me... hope you can imagine it