Spring Data JPA repositories
Get CRUD and derived queries without writing an implementation, and know where the line is.
Open this lesson in the learning hubKey points
- Extend
JpaRepository<Book, Long>and Spring generates the implementation at start-up. There is no class for you to write. - A method name is a query.
findByAuthorNameAndPagesGreaterThanresolves against the entity model, so a typo fails at boot. - Past three or four conditions the name stops reading like English. Move to
@Querywith JPQL and give the method a short name. save()on an entity with an id callsmerge, which may SELECT first. On a new one it callspersist.- Return
Optional, a projection or a DTO. Handing entities to a controller drags lazy proxies into serialization. - A repository is not worth mocking. Test it against a real database - the interesting bugs are in the SQL it generated.
Example
public interface BookRepository extends JpaRepository<Book, Long> {
// derived: parsed from the name at start-up, no body needed
Optional<Book> findByIsbn(String isbn);
List<Book> findByAuthorNameAndPagesGreaterThan(String name, int pages);
// the name would be unreadable, so say it in JPQL instead
@Query("select b from Book b join fetch b.author " +
"where b.publishedOn > :since order by b.publishedOn desc")
List<Book> recentWithAuthor(@Param("since") LocalDate since);
// read model: no entities, no lazy proxies, only two columns
@Query("select new com.app.BookView(b.title, a.name) " +
"from Book b join b.author a")
List<BookView> catalogue();
@Modifying
@Query("update Book b set b.archived = true where b.publishedOn < :cut")
int archiveOlderThan(@Param("cut") LocalDate cut);
}
The method name is the query. When the name turns ugly, write the JPQL.
This is a reading copy. The full lesson — with the visual explainer, the interactive lab and a Run button for the code — lives in the Hibernate course, and every lesson in it is listed on the Hibernate contents page.