0
0
Spring Bootframework~30 mins

@Query for custom JPQL in Spring Boot - Mini Project: Build & Apply

Choose your learning style9 modes available
Using @Query for Custom JPQL in Spring Boot
📖 Scenario: You are building a simple Spring Boot application to manage a list of books in a library. You want to find books by their author's name using a custom JPQL query.
🎯 Goal: Create a Spring Data JPA repository with a custom JPQL query using the @Query annotation to find books by author name.
📋 What You'll Learn
Create an entity class Book with fields id, title, and author.
Create a repository interface BookRepository that extends JpaRepository.
Add a custom method findBooksByAuthorName in BookRepository using @Query with JPQL.
Use the custom query to find all books by a given author.
💡 Why This Matters
🌍 Real World
Custom JPQL queries let you write precise database queries in Spring Boot applications, useful when default query methods are not enough.
💼 Career
Understanding @Query with JPQL is essential for backend developers working with Spring Data JPA to efficiently retrieve data from databases.
Progress0 / 4 steps
1
Create the Book entity
Create a class called Book annotated with @Entity. Add private fields Long id annotated with @Id and @GeneratedValue, String title, and String author. Include public getters and setters.
Spring Boot
Need a hint?

Use @Entity on the class. Use @Id and @GeneratedValue on the id field.

2
Create the BookRepository interface
Create an interface called BookRepository that extends JpaRepository<Book, Long>. This interface will be used to access the database.
Spring Boot
Need a hint?

Use public interface BookRepository extends JpaRepository<Book, Long>.

3
Add custom JPQL query method
Inside BookRepository, add a method List<Book> findBooksByAuthorName(String authorName) annotated with @Query. Use JPQL: "SELECT b FROM Book b WHERE b.author = :authorName".
Spring Boot
Need a hint?

Use @Query with JPQL string and @Param for the parameter.

4
Use the custom query method in a service
Create a class BookService with a private final BookRepository field. Add a constructor to inject BookRepository. Add a method List<Book> getBooksByAuthor(String authorName) that calls bookRepository.findBooksByAuthorName(authorName) and returns the result.
Spring Boot
Need a hint?

Use constructor injection for BookRepository and call the custom query method inside getBooksByAuthor.