Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Querying Data with a predicate and paging using Spring Data JPA

I have had the misfortune of working in Java for some time, coming from the .net world. Ranting aside, I am simply looking to implement a Repository that can handle use of predicates and must have pagination. I am unable to find a good way to do this.

// IContactRepository.java
public interface IContactRepository extends Repository<Contact,Long> {

}
// Application.java
contactRepo.findAll(predicate, new PageRequest(0,10));

I want to to be able to find contacts with contact name containing search term or contact phone number containing search term and then get first 10 matches.

In the .net world, if I was not using an orm I would use sql server's awesome TSQL to get what I want but stuck with Oracle here. I would otherwise use some ORM and pass a lambda to the query function as predicate.

like image 444
Perpetualcoder Avatar asked Mar 19 '23 06:03

Perpetualcoder


1 Answers

In my configuration I am also using JPA and spring. (FOR STATIC PREDICATES. If you want to add predicates(search terms) dynamically please let me know.)

// IContactRepository.java
public interface IContactRepository extends CrudRepository<Contact,Long>, PagingAndSortingRepository<Contact, Long>  {
    List<Contact> findByContactNameLikeAndContactPhoneLike(String name, String phone, Pageable pageable)
}

I tried Pageable with CrudRepo and it works fine. And for the lambda you are right :)

In my configuration your implementation looks like this :

IContactRepository contactRepo = context.getBean(IContactRepository.class);
List<Contacts> results = contactRepo.findByContactNameLikeAndContactPhoneLike("%CA%","%090%" , new PageRequest(1, 20));

http://docs.spring.io/spring-data/data-commons/docs/1.6.1.RELEASE/reference/html/repositories.html

Please have a look Query creation under 1.2.2 Defining query methods

like image 152
cgon Avatar answered Mar 22 '23 06:03

cgon