Derived Queries With Spring Data JPA
Derived Queries With Spring Data JPA
Spring Data often gets praised for its derived query feature. As long
as your method name starts with find…By, read…By, query…By,
count…By, or get…By and follows the right pattern, Spring Data
generates the required JPQL query.
That might sound like you will never need to write your own queries
again. But that’s not the case. It’s a great way to define simple
queries. But as soon as you need to use more than 2 query
parameters or your query gets at least a little bit complex, you should
use a custom query. That’s either because the query name gets really
complicated to write and read or because you exceed the capabilities
of the method name parser.
www.thoughts-on-java.org
Derived Queries with Spring Data JPA
public interface AuthorRepository extends JpaRepository<Author,
Long> {
www.thoughts-on-java.org
Derived Queries with Spring Data JPA
Between – to check if the value of an entity attribute is between
2 provided values.
LessThan / GreaterThan – to check if the value of an entity
attribute is less or greater then a provided one.
www.thoughts-on-java.org
Derived Queries with Spring Data JPA
Limiting the number of results
Using Hibernate or any other JPA implementation, you can limit the
number of returned records on the Query interface. With Spring
Data JPA, you can do the same by adding the keywords Top or First
followed by a number between the find and By keywords.
www.thoughts-on-java.org