Java / MapStruct Java Interview questions part 2
When should you use an expression inside @Mapping?
Use expression = "java(...)" when a target property's value can't be produced by simply copying or converting a single source property - for example, combining multiple fields, calling a static utility, or applying inline logic that's too small to justify a full default method.
@Mapping(target = "fullName", expression = "java(person.getFirstName() + \" \" + person.getLastName())") PersonDto toDto(Person person);
The string is inserted as raw Java into the generated method, so it is not type-checked until the mapper's generated source itself compiles - a typo inside the expression surfaces as a compile error in the generated class rather than in your own code. For anything longer than a one-liner, a default method is usually clearer and easier to test.
More Related questions...