In this post under MapStruct, I will show with example how to map a date as default and constant value.
Below is the source class
Student
package package23;
import java.util.Date;
public class Student {
private int id;
private String name;
//Removed getter, setter, and toString for brevity
}
The “Student” class has one field named “dol” of “Date” data type in addition to “id”, and “name” field.
Below is the destination class
StudentDTO
package package23;
import java.util.Date;
public class StudentDTO {
private int id;
private String name;
private Date doj;
private Date dol;
//Removed getter, setter, and toString for brevity
}
The “StudentDTO” class two fields named “doj” and “dol” of “Date” data type in addition to “id” and “name” field
Now we will assign a constant value to “doj” and a default value to “dol”.
Below is the mapper interface
StudentMapper
package package23;
import org.mapstruct.Mapper;
import org.mapstruct.Mapping;
@Mapper
public interface StudentMapper {
@Mapping(target = "doj", dateFormat = "yyyy-MM-dd", constant = "1981-12-10")
@Mapping(target = "dol", dateFormat = "yyyy-MM-dd", defaultValue = "1985-12-9")
StudentDTO getDTOFromModel(Student student);
}
In the above interface, I have used two “Mapping” annotation, one sets constant value “1981-12-10” to “doj” and another sets default value “1985-12-9” to “dol”.
Please note when the value to be set is a literal date value, we also need to mention the date format using “dateFormat” attribute as done in the above Mapper interface.
In this way we can map default and constant date values.