Databases Reference
In-Depth Information
Adding Querydsl support to a repository
We can add Querydsl support to a repository by extending the
QueryDslPredicateExecutor<T> interface. When we extend this interface we must
give the type of the managed entity as a type parameter. The source code of the
ContactRepository interface is given as follows:
public interface ContactRepository extends JpaRepository<Contact,
Long>, QueryDslPredicateExecutor<Contact> {
}
After we have extended the QueryDslPredicateExecutor<T> interface, we have
access to the following methods:
Method
Description
long count(Predicate p)
Returns the number of entities
matching with the given search criteria.
Iterable<Contact> findAll(Predicate
p)
Returns all entities matching with the
given search criteria.
Contact findOne(Predicate p)
Returns a single entity matching with
the given search criteria.
Creating the executed query
Each query must implement the Predicate interface that is provided by Querydsl.
Luckily, we don't have to implement this interface manually. Instead, we can use
the query types for creating the actual query objects. A clean way to do this is to
create a special predicate builder class and use a static method for creating the actual
predicates. Let's call this class ContactPredicates . Our implementation of the static
method that creates predicates fulfilling the requirements of the search function is
explained as follows:
1.
We implement a static firstOrLastNameStartsWith() method that returns
an implementation of the Predicate interface.
2.
We get a reference to the QContact query type.
3.
We build our query by using the QContact query type.
The source code of our predicate builder class is given as follows:
public class ContactPredicates {
public static Predicate firstOrLastNameStartsWith(final String
searchTerm) {
QContact contact = QContact.contact;
Search WWH ::




Custom Search