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.

Course – Black Friday 2026 – NPI EA – main – before_post_content
announcement - icon

Yes, we're now running our Black Friday Sale. All Courses are 33% off until 1st December, 2026 at 17:00 Romania time:

>> EXPLORE ACCESS NOW

Course – Black Friday 2026 – NPI – main – before_post_content
announcement - icon

Yes, we're now running our Black Friday Sale. All Courses are 33% off until 1st December, 2026 at 17:00 Romania time:

>> EXPLORE ACCESS NOW

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.
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.

Course – Black Friday 2026 – NPI EA – main – after_post_content

announcement - icon

Yes, we're now running our Black Friday Sale. All Courses are 33% off until 1st December, 2026 at 17:00 Romania time:

>> EXPLORE ACCESS NOW

Course – Black Friday 2026 – NPI – main – after_post_content

announcement - icon

Yes, we're now running our Black Friday Sale. All Courses are 33% off until 1st December, 2026 at 17:00 Romania time:

>> EXPLORE ACCESS NOW