Spring Data JPA Queries are a great way to create queries derived from the method name without needing to write tons of boiler-plate code to create connection & query, execute it and then process the result set. This generally works fine for simple queries and method names are very explicit in pointing out what is being returned by that method so the code is more readable and maintainable. To make this work successfully, the method name has to follow certain conventions:
- Method names usually start with the word "find"
- Filter clauses are added to the function name as "findBy<ColumnName>" which creates queries of the form "where <ColumnName> = ?"
- Multiple Filter clauses are supported using And / Or clauses
- And can be used as "findBy<Col1>And<Col2>" which creates the query "where <Col1> = ? and <Col2> = ?"
- Or can be used as "findBy<Col1>Or<Col2>" which creates the query "where <Col1> = ? or <Col2> = ?"
- Similarly other operators are supported on the lines of Between, After, Before, LessThan, GreaterThan, Like, etc
- Ordering of the results can be delegated to the database by adding "OrderBy" to the function name as "findBy<Col1>OrderBy<Col2><Asc|Desc><Col3><Asc|Desc>"
Keyword | Sample | JPQL snippet |
---|---|---|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|