Baeldung

Java, Spring and Web Development tutorials

 

TupleTransformer and ResultListTransformer in Hibernate
2025-09-13 14:36 UTC by Ulisses Lima

A robot with a vacuum hand that is pulling in various bits of data and outputing graphs and charts with its other hand. On the far left are the words "Data on Baeldung".

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.

As always, the source code is available over on GitHub.

The post TupleTransformer and ResultListTransformer in Hibernate first appeared on Baeldung.
       

 

Content mobilized by FeedBlitz RSS Services, the premium FeedBurner alternative.