Hello! Welcome back.
In our last lesson, we successfully modeled the one-to-many relationship between User and Post entities. Our application now understands that a user can have multiple posts. But how do we ask the database for specific data, like "find all posts by Jane Doe" or "find all posts with 'JPA' in the title"? Today, we'll answer that question.
This lesson directly addresses the learning outcome: Write custom repository queries using both derived query method names and the @Query annotation with JPQL. We'll explore the two primary ways Spring Data JPA allows you to define custom queries, moving from convention-over-configuration to full manual control.
MERN vs. Spring Boot: Querying Data
In your MERN stack experience, you're likely used to querying with Mongoose or the native MongoDB driver, where you construct a query object: db.posts.find({ title: /JPA/i }). This is a flexible, programmatic approach.
Spring Data JPA offers a different, more structured paradigm centered on repository interfaces. It provides two powerful mechanisms:
- Derived Query Methods: You define a method in your repository interface with a specific name, and Spring automatically writes and executes the corresponding SQL query. It's magic, driven by convention.
@QueryAnnotation: For complex queries that can't be expressed by a method name, you write the query yourself using JPQL (Java Persistence Query Language) or native SQL. This gives you complete control, similar to writing a complex aggregation pipeline in MongoDB.
Let's dive into the first method.
1. Derived Query Methods: Queries from Method Names
Spring Data JPA can parse the names of methods in your repository interfaces to figure out the query you want to run. The convention is find...By..., read...By..., get...By..., etc., followed by the entity's property names and keywords.
This visual guide breaks down the structure of these method names.

Let's implement this.
Step 1: Create the PostRepository
First, we need a repository for our Post entity. In your repository package, create a new interface named PostRepository.java.
package com.example.blogplatform.repository;
import com.example.blogplatform.domain.Post;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
@Repository
public interface PostRepository extends JpaRepository<Post, Long> {
// We will add our custom query methods here
}
That's it. By extending JpaRepository, we already have methods like findAll(), findById(), save(), and delete().
Step 2: Implement a Simple Derived Query
Let's find posts by their title. Add the following method to PostRepository:
import java.util.List;
// ... inside PostRepository interface
List<Post> findByTitle(String title);
Spring Data JPA sees this method and understands it needs to generate a query equivalent to SELECT * FROM posts WHERE title = ?. The parameter String title will be used as the value for the WHERE clause.
Step 3: Combining Conditions and Adding Operators
Now for something more complex. Let's find all posts by a specific user, but only those whose titles contain a certain keyword (ignoring case), and order them by creation date descending.
Add this method to PostRepository:
import com.example.blogplatform.domain.User;
import java.util.List;
// ... inside PostRepository interface
List<Post> findByUserAndTitleContainingIgnoreCaseOrderByCreatedAtDesc(User user, String titleKeyword);
Let's break down this powerful method name:
findByUser...: Filter by theUserobject....AndTitle...: Combine the user filter with a filter on thetitleproperty....ContainingIgnoreCase...: Use aLIKEcomparison for the title, and make it case-insensitive....OrderByCreatedAtDesc: Order the results by thecreatedAtproperty in descending order.
The parameters User user and String titleKeyword map directly to the conditions in the method name, in order.
This table provides a great reference for the keywords you can use.

For a comprehensive walkthrough of the possibilities with derived queries and the @Query annotation, the following video is an excellent resource.
Spring Data JPA Implementation: Full Guide with CrudRepository, Paging, Sorting & Query Methods
This video provides a great practical guide to implementing various repository types and query methods in Spring Data JPA. We'll be focusing on the sections covering derived queries and @Query.
Please watch the sections on derived query methods (39:11 - 47:02) and custom queries with @Query (47:02 - 49:55). Pay attention to: How the method name findByStatus is automatically translated into a SQL query. The use of OrderBy to sort results. How @Query is used for a more complex query (LIKE search) that is difficult to express with a method name.
2. Debugging-First: See Derived Queries in Action
Let's test our new methods and see what happens when things go wrong.
Step 1: Prepare Test Data
Update DataInitializer.java to create a more diverse set of data to query against. Replace its content with this:
package com.example.blogplatform;
import com.example.blogplatform.domain.Post;
import com.example.blogplatform.domain.User;
import com.example.blogplatform.repository.PostRepository;
import com.example.blogplatform.repository.UserRepository;
import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Component;
import java.util.List;
@Component
public class DataInitializer implements CommandLineRunner {
private final UserRepository userRepository;
private final PostRepository postRepository;
public DataInitializer(UserRepository userRepository, PostRepository postRepository) {
this.userRepository = userRepository;
this.postRepository = postRepository;
}
@Override
public void run(String... args) throws Exception {
// Clean up
postRepository.deleteAll();
userRepository.deleteAll();
// Create Users
User user1 = new User("john.doe@example.com", "John", "Doe", "password123");
User user2 = new User("jane.smith@example.com", "Jane", "Smith", "password456");
// Create Posts for John
Post post1 = new Post("JPA Basics", "An intro to JPA.");
Post post2 = new Post("Spring Data JPA", "Querying data with Spring.");
user1.addPost(post1);
user1.addPost(post2);
// Create Posts for Jane
Post post3 = new Post("Advanced JPA", "Deep dive into JPA performance.");
user2.addPost(post3);
userRepository.saveAll(List.of(user1, user2));
System.out.println("--- TESTING DERIVED QUERIES ---");
// Test 1: Find by exact title
List<Post> jpaBasicsPosts = postRepository.findByTitle("JPA Basics");
System.out.println("Found posts with title 'JPA Basics': " + jpaBasicsPosts.size());
// Test 2: Find by user and title keyword, ordered
List<Post> johnsPostsWithJpa = postRepository.findByUserAndTitleContainingIgnoreCaseOrderByCreatedAtDesc(user1, "jpa");
System.out.println("Found posts by John containing 'jpa': " + johnsPostsWithJpa.size());
johnsPostsWithJpa.forEach(p -> System.out.println("\t- " + p.getTitle()));
}
}
Note: You may need to add a constructor public User(String email, String firstName, String lastName, String password) to your User entity for this to work.
Now, run the application. Check the console output. You'll see the test results, and more importantly, in the logs, you'll see the SQL that Hibernate generated for your methods!
For findByTitle:... where p1_0.title=?
For findByUserAndTitleContainingIgnoreCaseOrderByCreatedAtDesc:... where p1_0.user_id=? and upper(p1_0.title) like upper(?) order by p1_0.created_at desc
This runtime observation confirms the "magic" is working as expected.
Debugging Task: The PropertyReferenceException
- Stop the application.
- In
PostRepository, introduce a typo in a method name. ChangefindByTitletofindByTitl(missing 'e'). - Try to run the application again.
The application will fail to start. Look at the stack trace in your console. You will find an error message like this:
Caused by: org.springframework.data.mapping.PropertyReferenceException: No property 'titl' found for type 'Post'! Did you mean 'title'?
This is Spring Data JPA telling you that it couldn't find a property named titl on the Post entity when it tried to parse your method name. This is a common and easy-to-fix error. The IDE won't catch this, but the application startup process will.
Fix the typo before proceeding.
3. Custom Queries with @Query and JPQL
Derived queries are fantastic for simple-to-medium complexity. But what if you need a query that's too complex for a method name? For instance, searching for a keyword in either the title or the content.
This is where @Query comes in, allowing you to write your own JPQL (Java Persistence Query Language) statement.
Step 1: Write a JPQL Query
Let's implement the keyword search. Add this method to PostRepository:
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
// ... inside PostRepository interface
@Query("SELECT p FROM Post p WHERE lower(p.title) LIKE lower(concat('%', :keyword, '%')) OR lower(p.content) LIKE lower(concat('%', :keyword, '%'))")
List<Post> findByTitleOrContentKeyword(@Param("keyword") String keyword);
Let's break this down:
@Query(...): This annotation holds our custom query."SELECT p FROM Post p ...": This is JPQL. It looks like SQL, but it operates on your Java entities, not database tables.Postis thePostclass, andpis an alias for it.p.titlerefers to thetitlefield in thePostclass.:keyword: This is a named parameter. It's a placeholder in the query.@Param("keyword") String keyword: This annotation links the method parameterkeywordto the named parameter:keywordin the query.lower(...)andconcat('%', ..., '%'): These are JPQL functions, similar to their SQL counterparts, used here to perform a case-insensitiveLIKEsearch.
For a deeper dive into the power of @Query, this article is an excellent reference.
Ultimate Guide: Custom Queries with Spring Data JPA’s @Query Annotation
This article from Thorben Janssen, a JPA expert, is an ultimate guide to using the @Query annotation. It covers everything from basic JPQL to advanced features.
Please read the sections "Defining a Custom JPQL Query" and "Parameter Handling". Focus on: The basic syntax of a JPQL query inside the @Query annotation. The difference between referencing the entity name (e.g., FROM Author) and using #{#entityName}. The two ways of handling parameters: positional (?1) and named (:name), and why named parameters are preferred.
Conclusion
Great job! You've mastered the two essential techniques for querying data in a Spring Boot application.
Key Takeaways:
- Derived Queries are perfect for simple, readable queries where the conditions map directly to entity properties. They enforce a strong convention.
@Querywith JPQL provides the power and flexibility to write any query you can imagine, operating on your object model rather than raw tables.- Debugging startups is key. A
PropertyReferenceExceptionmeans a typo in a derived query name, while aQuerySyntaxExceptionpoints to an error in your JPQL string. - Always inspect the logs to see the final SQL generated by Hibernate. This is your ground truth for understanding what the application is doing.
Preview of the Next Lesson:
We can now fetch data efficiently. However, when we fetch entities that have relationships (like fetching a Post and accessing its User), a hidden performance monster can appear: the N+1 query problem. In our next lesson, we will identify this problem by observing our SQL logs and fix it using JOIN FETCH within our @Query annotations, a crucial skill for any backend developer.