The best way to write a custom Spring Data Repository

Imagine having a tool that can automatically detect JPA and Hibernate performance issues. Wouldn’t that be just awesome?

Well, Hypersistence Optimizer is that tool! And it works with Spring Boot, Spring Framework, Jakarta EE, Java EE, Quarkus, or Play Framework.

So, enjoy spending your time on the things you love rather than fixing performance issues in your production system on a Saturday night!


In this article, I’m going to show you the best way to write a custom Spring Data Repository.

While the default JpaRepository methods, as well as the query methods, are very convenient in many situations, there might be times when you need custom Repository methods that can take advantage of any JPA provider-specific functionality.

When to use a custom Spring Data Repository

Let’s assume we want to fetch a one-to-many DTO projection, as I explained in this article.

Our JPA query looks like this:

List<PostDTO> postDTOs = entityManager.createQuery("""
    select as p_id,
           p.title as p_title,
  as pc_id,
  as pc_review
    from PostComment pc
    join p
    order by
.setResultTransformer(new PostDTOResultTransformer())

Notice that we are unwrapping the JPA Query to a Hibernate org.hibernate.query.Query in order to provide a custom ResultTransformer that can build a hierarchical parent-child DTO aggregate from the default table-based Object[] projection.

We can’t just use a regular Spring Data Repository query method or a @Query annotation because we also have to pass our own Hibernate-specific ResultTransformer.

Therefore, we need to write a custom Repository that can provide us access to the underlying JPA EntityManager so that we can write our query using the Hibernate-specific API.

How to write a custom Spring Data Repository

First, we need to define an interface that provides the method signatures of our custom Repository methods.

public interface CustomPostRepository {

    List<PostDTO> findPostDTOWithComments();

Second, we need to provide an implementation of the CustomPostRepository interface:

public class CustomPostRepositoryImpl implements CustomPostRepository {
    private EntityManager entityManager;

    public List<PostDTO> findPostDTOWithComments() {
        return entityManager.createNativeQuery("""
            SELECT AS p_id, 
                   p.title AS p_title,
          AS pc_id, 
          AS pc_review
            FROM post p
            JOIN post_comment pc ON = pc.post_id
            ORDER BY
        .setResultTransformer(new PostDTOResultTransformer())

Third, we need to make the default Spring Data JPA PostRepository extend our CustomPostRepository interface:

public interface PostRepository 
    extends JpaRepository<Post, Long>, CustomPostRepository {

A picture is worth 100 words, so here’s a diagram that shows you how the custom Spring Data Repository is associated to the standard JpaRepository one:

Custom Spring Data Repository class relationship

Testing time

Assuming we have two Post entities, the first one having two PostComment child entities, and the second Post having a single PostComment child:

    new Post()
        .setTitle("High-Performance Java Persistence")
            new PostComment()
                .setReview("Best book on JPA and Hibernate!")
            new PostComment()
                .setReview("A must-read for every Java developer!")

    new Post()
        .setTitle("Hypersistence Optimizer")
            new PostComment()
                .setReview("It's like pair programming with Vlad!")

When calling the findPostDTOWithComments method, we are going to get the expected PostDTO hierarchical projection:

List<PostDTO> postDTOs = forumService.findPostDTOWithComments();

assertEquals(2, postDTOs.size());
assertEquals(2, postDTOs.get(0).getComments().size());
assertEquals(1, postDTOs.get(1).getComments().size());

PostDTO post1DTO = postDTOs.get(0);

assertEquals(1L, post1DTO.getId().longValue());
assertEquals(2, post1DTO.getComments().size());
assertEquals(1L, post1DTO.getComments().get(0).getId().longValue());
assertEquals(2L, post1DTO.getComments().get(1).getId().longValue());

PostDTO post2DTO = postDTOs.get(1);

assertEquals(2L, post2DTO.getId().longValue());
assertEquals(1, post2DTO.getComments().size());
assertEquals(3L, post2DTO.getComments().get(0).getId().longValue());

Cool, right?

I'm running an online workshop on the 11th of October about High-Performance SQL.

If you enjoyed this article, I bet you are going to love my Book and Video Courses as well.


While it’s very common to see standard Spring Data repositories that extend the JpaRepository interface, a custom Repository can allow you to take advantage of all the features provided by JPA or the underlying JPA provider.

Transactions and Concurrency Control eBook

3 Comments on “The best way to write a custom Spring Data Repository

  1. Hey Vlad!
    In the example the original JPQL query was changed to native query?
    Is there any reason behind that?

    • It doesn’t matter whether you use JPQL or native SQL when it comes to fetching projections.

      The goal of the article is to show how to use Custom Repository, the rest is just supporting the story.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.