MicroLova
MicroLova

Reputation: 361

Spring Boot JPA find, filter

As Spring jpa Provides some usefull features to find Items from a repository by defining it in the method name. e .x findByTitle(String title) then Spring is automatically searching the Title Colum for the given String. If i have an int column named numberOfCopies and i want only to find the datasets with >0 greater then null how would define such a method ?

to filter out those books with the numberOfCopies equals 0 = zero

@Entity
public class Book {
    @Id
    private int id;
    private String title;
    private int numberOfCopies;
}

can i use the Repomethod

public List findBooksByNumberOfCopies.greater then 0 ?To Use this Spring Feature without some if or for loops

Upvotes: 0

Views: 1879

Answers (4)

Syrup72
Syrup72

Reputation: 126

GreaterThanEqual takes an Integer not int

List<Book> findByNumberOfCopiesGreaterThanEqual(Integer numberOfCopies);

Upvotes: 0

bur&#230;quete
bur&#230;quete

Reputation: 14698

First, you should use Integer, since it is better, in my opinion, to use wrapper classes than to primitives, and enforce not null requirement through annotations, e.g. @Column(nullable = false)

@Entity
public class Book {

    @Id
    private Integer id;
    private String title;
    private Integer numberOfCopies;
}

Then you can add the following two methods in your BookRepository;

List<Book> findByNumberOfCopiesGreaterThan(Integer numberOfCopies);

default List<Book> findAllAvailableBooks() {
    return findByNumberOfCopiesGreaterThan(0);
}

and use the default findAllAvailableBooks method, with hardcoded 0 value which is your requirement.

Upvotes: 1

Christian Meyer
Christian Meyer

Reputation: 625

Pretty sure this would work:

public interface BookRepo extends JpaRepository<Book, Integer> {

   @Query("SELECT b FROM Book b WHERE b.numberOfCopies >= 0")
   public Optional<List<Book>> getTheBooksWithMultCopies();

}

// back in your component class:
{
   ...
   Optional<List<Book>> optionalBookList = myBookRepo.getTheBooksWithMultCopies();
   if (optionalBookList.isPresent()){
      List<Book> bookList = optionalBookList.get();
   }
}

Note that the language within the query is called HQL, which is what is used by Hibernate internally (which is used by JPA internally). It's really not very intimidating - just, know that you the objects in your POJO, which map to your database table, rather than your database table directly.

Also, I'd recommend using Integer over int in entity classes, at least if your value is nullable. Otherwise, numberOfCopies will always default to 0, which may not be desirable and may cause exceptions that are difficult to decipher.

Upvotes: 0

Khaled Baklouti
Khaled Baklouti

Reputation: 418

you can easily use

List<Book> findByNumberOfCopiesGreaterThanEqual(int numberOfCopies);

Upvotes: 0

Related Questions