Mapping between objects with expressions

In this post under MapStruct, I will show with example how to add expressions in “@Mapping” annotation.

For our example we will use the below classes

Student

package package24;

import java.util.Date;

public class Student {
    private int id;
    private String name;

    //Removed getter, setter, and toString for brevity
}

StudentDTO

package package24;

import java.util.Date;

public class StudentDTO {
    private int id;
    private String name;
    private Date doj;

    //Removed getter, setter, and toString for brevity
}

We will be mapping “Student” instance to “StudentDTO” instance.

In the class “StudentDTO” we have “doj” field which we will set to current datetime through expressions.

Below is the mapper interface

StudentMapper

package package24;

import org.mapstruct.Mapper;
import org.mapstruct.Mapping;

@Mapper
public interface StudentMapper {
    @Mapping(target = "doj", expression = "java(new java.util.Date())")
    StudentDTO getDTOFromModel(Student student);
}

In the above Mapper interface, we are setting the field “doj” with current date time using expression.

The expression must be sorrounded by “java(” and “)”.

“java” is mentioned to tell MapStruct that we have written the expression using Java programming language.

In this way we can use expressions when coming up with Mapper interface.

Below is the main class for your reference

Main class

package package24;

import org.mapstruct.factory.Mappers;

public class Example24 {
    public static void main(String[] args) {
        StudentMapper studentMapper = Mappers.getMapper(StudentMapper.class);

        Student student = new Student();
        student.setId(1);
        student.setName("John Doe");

        StudentDTO studentDTO = studentMapper.getDTOFromModel(student);

        System.out.println(studentDTO);
    }
}

Below is the output for your reference

Output

1-John Doe-Sat Jun 28 08:11:05 IST 2025

Leave a comment