eBook – Guide Spring Cloud – NPI EA (cat=Spring Cloud)
announcement - icon

Let's get started with a Microservice Architecture with Spring Cloud:

>> Join Pro and download the eBook

eBook – Mockito – NPI EA (tag = Mockito)
announcement - icon

Mocking is an essential part of unit testing, and the Mockito library makes it easy to write clean and intuitive unit tests for your Java code.

Get started with mocking and improve your application tests using our Mockito guide:

Download the eBook

eBook – Java Concurrency – NPI EA (cat=Java Concurrency)
announcement - icon

Handling concurrency in an application can be a tricky process with many potential pitfalls. A solid grasp of the fundamentals will go a long way to help minimize these issues.

Get started with understanding multi-threaded applications with our Java Concurrency guide:

>> Download the eBook

eBook – Reactive – NPI EA (cat=Reactive)
announcement - icon

Spring 5 added support for reactive programming with the Spring WebFlux module, which has been improved upon ever since. Get started with the Reactor project basics and reactive programming in Spring Boot:

>> Join Pro and download the eBook

eBook – Java Streams – NPI EA (cat=Java Streams)
announcement - icon

Since its introduction in Java 8, the Stream API has become a staple of Java development. The basic operations like iterating, filtering, mapping sequences of elements are deceptively simple to use.

But these can also be overused and fall into some common pitfalls.

To get a better understanding on how Streams work and how to combine them with other language features, check out our guide to Java Streams:

>> Join Pro and download the eBook

eBook – Jackson – NPI EA (cat=Jackson)
announcement - icon

Do JSON right with Jackson

Download the E-book

eBook – HTTP Client – NPI EA (cat=Http Client-Side)
announcement - icon

Get the most out of the Apache HTTP Client

Download the E-book

eBook – Maven – NPI EA (cat = Maven)
announcement - icon

Get Started with Apache Maven:

Download the E-book

eBook – Persistence – NPI EA (cat=Persistence)
announcement - icon

Working on getting your persistence layer right with Spring?

Explore the eBook

eBook – RwS – NPI EA (cat=Spring MVC)
announcement - icon

Building a REST API with Spring?

Download the E-book

Course – LS – NPI EA (cat=Jackson)
announcement - icon

Get started with Spring and Spring Boot, through the Learn Spring course:

>> LEARN SPRING
Course – RWSB – NPI EA (cat=REST)
announcement - icon

Explore Spring Boot 3 and Spring 6 in-depth through building a full REST API with the framework:

>> The New “REST With Spring Boot”

Course – LSS – NPI EA (cat=Spring Security)
announcement - icon

Yes, Spring Security can be complex, from the more advanced functionality within the Core to the deep OAuth support in the framework.

I built the security material as two full courses - Core and OAuth, to get practical with these more complex scenarios. We explore when and how to use each feature and code through it on the backing project.

You can explore the course here:

>> Learn Spring Security

Course – LSD – NPI EA (tag=Spring Data JPA)
announcement - icon

Spring Data JPA is a great way to handle the complexity of JPA with the powerful simplicity of Spring Boot.

Get started with Spring Data JPA through the guided reference course:

>> CHECK OUT THE COURSE

Partner – Moderne – NPI EA (cat=Spring Boot)
announcement - icon

Refactor Java code safely — and automatically — with OpenRewrite.

Refactoring big codebases by hand is slow, risky, and easy to put off. That’s where OpenRewrite comes in. The open-source framework for large-scale, automated code transformations helps teams modernize safely and consistently.

Each month, the creators and maintainers of OpenRewrite at Moderne run live, hands-on training sessions — one for newcomers and one for experienced users. You’ll see how recipes work, how to apply them across projects, and how to modernize code with confidence.

Join the next session, bring your questions, and learn how to automate the kind of work that usually eats your sprint time.

Partner – LambdaTest – NPI EA (cat=Testing)
announcement - icon

Regression testing is an important step in the release process, to ensure that new code doesn't break the existing functionality. As the codebase evolves, we want to run these tests frequently to help catch any issues early on.

The best way to ensure these tests run frequently on an automated basis is, of course, to include them in the CI/CD pipeline. This way, the regression tests will execute automatically whenever we commit code to the repository.

In this tutorial, we'll see how to create regression tests using Selenium, and then include them in our pipeline using GitHub Actions:, to be run on the LambdaTest cloud grid:

>> How to Run Selenium Regression Tests With GitHub Actions

Course – LJB – NPI EA (cat = Core Java)
announcement - icon

Code your way through and build up a solid, practical foundation of Java:

>> Learn Java Basics

1. Introduction

In this tutorial, we’ll explore how to work with TupleTransformer for row-level transformations and ResultListTransformer for list-level processing. While JPQL projections solve many cases, sometimes we need more flexibility, like mapping complex DTOs, restructuring query results, or post-processing the entire result set.

2. Scenario and Setup

Before Hibernate 6, custom result mappings were handled by the ResultTransformer interface. This was powerful but overloaded, as it handled both per-row and per-list transformations.

In 6, these responsibilities are split into two interfaces:

Based on the Baeldung University schema, let’s now map and transform our entities into DTOs using these new Hibernate interfaces.

2.1. Creating the Entities

We’ll start with a scenario where each student has a home department where they’re enrolled:

@Entity
public class Department {

    @Id
    @GeneratedValue
    Long id;

    String name;

    @OneToMany(mappedBy = "department")
    List<Student> students;

    // standard getters, setters, and constructors
}

For example, a student might be in the Computer Science Department, pursuing a BS in Computer Science:

@Entity
public class Student {

    @Id
    @GeneratedValue
    Long id;

    String name;

    @ManyToOne
    Department department;

    // standard getters, setters, and constructors
}

Finally, a simple DTO to reference in transformations:

public record StudentDto(Long id, String name) {}

2.2. Loading the Test Data

Our data involves enrolling some Students into Courses and allocating them into Departments:

@Transactional
@SpringBootTest
class HibernateTransformersIntegrationTest {

    @PersistenceContext
    EntityManager em;

    @BeforeEach
    void setUp() {
        Department cs = new Department("Computer Science");
        Department math = new Department("Mathematics");
        em.persist(cs);
        em.persist(math);

        Student alice = new Student("Alice", cs);
        Student bob = new Student("Bob", cs);
        Student carol = new Student("Carol", math);
        em.persist(alice);
        em.persist(bob);
        em.persist(carol);
    }

    // ...
}

This is just enough so we can see how a TupleTransformer works.

3. Using the TupleTransformer

A TupleTransformer defines a transformation we want applied to each result of a query. Also, this is applied before the results are packaged in a List and returned. Most importantly, each result is received as an Object[], which we can transform into any other type.

3.1. Mapping the Results of a Simple Query

To implement a TupleTransformer from a query created with an EntityManager, we first need to call unwrap() to access Hibernate’s API. Then, we use setTupleTransformer(), which lets us access each row and its column aliases:

@Test
void whenUsingTupleTransformer_thenMapToStudentDto() {
    List<StudentDto> results = em.createQuery("SELECT s.id, s.name FROM Student s")
      .unwrap(Query.class)
      .setTupleTransformer(
        (tuple, aliases) -> new StudentDto((Long) tuple[0], (String) tuple[1]))
      .getResultList();

    assertEquals(3, results.size());
}

Each row is mapped into a StudentDto by accessing the columns by index.

3.2. Using Column Aliases to Map by Name

If we define aliases for our query, we can map our DTO more safely by using the aliases array:

String query = "SELECT s.id AS studentId, s.name AS studentName FROM Student s";

Then, we create the query as usual:

em.createQuery(query).unwrap(Query.class)
  .setTupleTransformer((tuple, aliases) -> {
      // ...
  })
  .getResultList();

The TupleTransformer gives us complete freedom in how we map our rows. Let’s first create a map, collecting each column value to a key with its alias:

Map<String, Object> row = IntStream.range(0, aliases.length).boxed()
  .collect(Collectors.toMap(i -> aliases[i], i -> tuple[i]));

Finally, we can access our DTO’s properties by their name:

return new StudentDto((Long) row.get("studentId"), (String) row.get("studentName"));

This avoids mistakes from index-based access and is especially useful for DTOs with many fields.

4. Using the ResultListTransformer to Group Results

The ResultListTransformer acts as a post-processor on the result list, giving us flexibility beyond what SQL can easily express. Let’s create a DTO that holds a Department plus a list of Students for each row:

public record DepartmentStudentsDto(String department, List<String> students) {}

Now, let’s use it to group rows into this higher-level structure:

em.createQuery("SELECT d.name, s.name FROM Department d JOIN d.students s")
  .unwrap(Query.class)
  .setTupleTransformer(
    (tuple, aliases) -> new AbstractMap.SimpleEntry<>((String) tuple[0], (String) tuple[1]))
  .setResultListTransformer(list -> ((List<Map.Entry<String, String>>) list).stream()
    .collect(groupingBy(Map.Entry::getKey, mapping(Map.Entry::getValue, toList())))
    .entrySet()
    .stream().map(e -> new DepartmentStudentsDto(e.getKey(), e.getValue()))
    .toList())
  .getResultList();

Breaking this down: we start with (department name, student name) entries, group them by department, and collect students into lists. The result is a Map<String, List<String>> that we then map into DTOs:

{
  "Computer Science" -> ["Alice", "Bob"],
  "Mathematics" -> ["Carol"]
}

In most cases, grouping should be done on the database with JPQL aggregates, since databases are optimized for set operations. However, setResultListTransformer() is useful when the grouping logic doesn’t map neatly to SQL, like when building this nested DTO, or applying transformations after row-level processing.

5. Using the ResultListTransformer to Remove Duplicates

To demonstrate deduplication, we introduce two entities: Course and Enrollment. A course can have many enrolled students, and a student can enroll in multiple courses.

5.1. Creating the Relationships

We’ll start simple by only including the Course’s name and ID:

@Entity
public class Course {

    @Id
    @GeneratedValue
    Long id;

    String name;

    // standard getters, setters, and constructors
}

Then, the Enrollment entity with @ManyToOne annotations for Student and Course:

@Entity
public class Enrollment {

    @Id
    @GeneratedValue
    Long id;

    @ManyToOne
    Student student;

    @ManyToOne
    Course course;

    // standard getters, setters, and constructors
}

5.2. Inserting New Test Data

Let’s go back to our setup method and insert Enrollment relationships:

@BeforeEach
void setUp() {
    //...

    Course algorithms = new Course("Algorithms", cs);
    Course calculus = new Course("Calculus", math);
    em.persist(algorithms);
    em.persist(calculus);

    em.persist(new Enrollment(alice, algorithms));
    em.persist(new Enrollment(alice, calculus));
    em.persist(new Enrollment(bob, algorithms));
    em.persist(new Enrollment(carol, calculus));
}

5.3. Creating the ResultListTransformer

If we query enrollments and join students, the same student appears once for each course they’re enrolled in, leading to duplicates. This makes Enrollment a natural example for showing how to eliminate duplicates with a ResultListTransformer:

String query = "SELECT s.id, s.name FROM Enrollment e JOIN e.student s";

When we call setResultListTransformer(), we can access the results stream. Let’s do some post-processing and call distinct() on the results:

List results = em.createQuery(query)
  .unwrap(Query.class)
  .setTupleTransformer((tuple, aliases) -> new StudentDto((Long) tuple[0], (String) tuple[1]))
  .setResultListTransformer(list -> list.stream()
    .distinct()
    .toList())
  .getResultList();

The distinct() works here because Java records implicitly implement equals() by comparing every field:

assertEquals(3, results.size());

Using distinct directly in the SQL query is more efficient, but ResultListTransformer is useful when deduplication must happen after DTO transformation.

6. Conclusion

In this article, we explored how Hibernate distinguishes between per-row and per-list transformations. We saw how TupleTransformer can safely map query results into DTOs, even leveraging aliases for robustness, and how ResultListTransformer can remove duplicates or group results into higher-level structures. These tools give us flexible ways to tailor query output to application needs without overcomplicating entity models or queries.

The code backing this article is available on GitHub. Once you're logged in as a Baeldung Pro Member, start learning and coding on the project.
Baeldung Pro – NPI EA (cat = Baeldung)
announcement - icon

Baeldung Pro comes with both absolutely No-Ads as well as finally with Dark Mode, for a clean learning experience:

>> Explore a clean Baeldung

Once the early-adopter seats are all used, the price will go up and stay at $33/year.

eBook – HTTP Client – NPI EA (cat=HTTP Client-Side)
announcement - icon

The Apache HTTP Client is a very robust library, suitable for both simple and advanced use cases when testing HTTP endpoints. Check out our guide covering basic request and response handling, as well as security, cookies, timeouts, and more:

>> Download the eBook

eBook – Java Concurrency – NPI EA (cat=Java Concurrency)
announcement - icon

Handling concurrency in an application can be a tricky process with many potential pitfalls. A solid grasp of the fundamentals will go a long way to help minimize these issues.

Get started with understanding multi-threaded applications with our Java Concurrency guide:

>> Download the eBook

eBook – Java Streams – NPI EA (cat=Java Streams)
announcement - icon

Since its introduction in Java 8, the Stream API has become a staple of Java development. The basic operations like iterating, filtering, mapping sequences of elements are deceptively simple to use.

But these can also be overused and fall into some common pitfalls.

To get a better understanding on how Streams work and how to combine them with other language features, check out our guide to Java Streams:

>> Join Pro and download the eBook

eBook – Persistence – NPI EA (cat=Persistence)
announcement - icon

Working on getting your persistence layer right with Spring?

Explore the eBook

Course – LS – NPI EA (cat=REST)

announcement - icon

Get started with Spring Boot and with core Spring, through the Learn Spring course:

>> CHECK OUT THE COURSE

Partner – Moderne – NPI EA (tag=Refactoring)
announcement - icon

Modern Java teams move fast — but codebases don’t always keep up. Frameworks change, dependencies drift, and tech debt builds until it starts to drag on delivery. OpenRewrite was built to fix that: an open-source refactoring engine that automates repetitive code changes while keeping developer intent intact.

The monthly training series, led by the creators and maintainers of OpenRewrite at Moderne, walks through real-world migrations and modernization patterns. Whether you’re new to recipes or ready to write your own, you’ll learn practical ways to refactor safely and at scale.

If you’ve ever wished refactoring felt as natural — and as fast — as writing code, this is a good place to start.

eBook Jackson – NPI EA – 3 (cat = Jackson)