Convert String to Date Using MapStruct in Java
MapStruct is a tool in Java that simplifies the process of object-to-object mapping. It is often used in applications to transfer data between layers or convert Data Transfer Objects (DTOs) into entities.
In Java applications, we often encounter scenarios where we need to map fields between objects, especially when converting data between different formats. One such scenario is when we have a String
in one class (source) that we need to convert to a Date
in another class (target). This article explains how to convert a String to a Date using MapStruct.
1. The Problem
We have a source class with a String
field representing a date in the format "yyyy-MM-dd"
. Our target class needs this field to be mapped to a java.util.Date
object.
1.1 Prerequisite
Be sure to add the following dependency to your pom.xml
if you are using Maven, and also set up maven-compiler-plugin
to include the MapStruct processor.
<dependencies> <!-- MapStruct core library --> <dependency> <groupId>org.mapstruct</groupId> <artifactId>mapstruct</artifactId> <version>1.5.5.Final</version> <!-- Check for the latest version --> </dependency> </dependencies> <build> <plugins> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-compiler-plugin</artifactId> <version>3.13.0</version> <configuration> <annotationProcessorPaths> <path> <!-- MapStruct Processor, which generates the code for mapping --> <groupId>org.mapstruct</groupId> <artifactId>mapstruct-processor</artifactId> <version>1.5.5.Final</version> </path> </annotationProcessorPaths> </configuration> </plugin> </plugins> </build>
This configuration enables Maven to use the MapStruct processor to automatically generate the mapper implementation code from our interfaces. Without this, the MapStruct annotations won’t be processed correctly, and the code for the mapping will not be generated. The version 1.5.5.Final
must match the MapStruct core library’s version to ensure compatibility.
2. Define the Domain Model and DTO
We will define a PersonDto
class with a String
birth date, a Person
class with a Date
birth date, and create a PersonMapper
interface that uses the @Mapping
annotation to specify the date format for the conversion.
public class PersonDto { private String name; // Date in String format private String birthDate; public String getName() { return name; } public void setName(String name) { this.name = name; } public String getBirthDate() { return birthDate; } public void setBirthDate(String birthDate) { this.birthDate = birthDate; } }
public class Person { private String name; private Date birthDate; // Getters and Setters public String getName() { return name; } public void setName(String name) { this.name = name; } public Date getBirthDate() { return birthDate; } public void setBirthDate(Date birthDate) { this.birthDate = birthDate; } }
3. Create the Mapper Interface
Next, we will create a mapper interface that uses MapStruct to define the mapping between UserDTO
and User
. We will use MapStruct’s @Mapper
and @Mapping
annotations to define the mapping logic. Specifically, we will define that the birthDate
from PersonDto
(which is a String
) should be converted to a Date
in Person
using the specified format ("yyyy-MM-dd"
).
import org.mapstruct.Mapper; import org.mapstruct.Mapping; import org.mapstruct.factory.Mappers; @Mapper public interface PersonMapper { PersonMapper INSTANCE = Mappers.getMapper(PersonMapper.class); @Mapping(source = "birthDate", target = "birthDate", dateFormat = "yyyy-MM-dd") Person toPerson(PersonDto personDto); }
3.1 Using the Mapper
With our mapper now set up, let’s look at how we can use it in our application.
public class MapstructExample { public static void main(String[] args) { // Create a PersonDto object with a birthDate as String PersonDto personDto = new PersonDto(); personDto.setName("John Fish"); personDto.setBirthDate("1983-05-11"); // Use the generated mapper to map PersonDto to Person Person person = PersonMapper.INSTANCE.toPerson(personDto); System.out.println("Name: " + person.getName()); System.out.println("Birth Date: " + person.getBirthDate()); } }
Output
The above class outputs the following:
The Person
object has the birthDate
as a Date
, which is printed in the default Date
format (Wed May 11 00:00:00 WAT 1983
).
4. Implementing Custom Mapping Logic
If we need more control over how data is converted, we can implement custom conversion methods.
@Mapper public interface PersonMapper { PersonMapper INSTANCE = Mappers.getMapper(PersonMapper.class); @Mapping(target = "birthDate", expression = "java(map(personDto.getBirthDate()))") Person toPerson(PersonDto personDto); default Date map(String value) { if (value == null || value.isEmpty()) { return null; } try { SimpleDateFormat sdf = new SimpleDateFormat("dd-MM-yyyy"); return sdf.parse(value); } catch (ParseException e) { throw new RuntimeException("Failed to parse date: " + value, e); } } }
In this code snippet, the line @Mapping(target = "birthDate", expression = "java(map(personDto.getBirthDate()))")
specifies how to map the birthDate
property from the PersonDto
to the Person
object in the toPerson
method. Instead of using a simple property mapping, this annotation employs a custom expression that invokes the map
method to convert the String
representation of the birth date from the PersonDto
into a Date
object for the Person
.
5. Conclusion
In this article, we explored how to convert a String to a Date using MapStruct in Java. By defining the necessary classes and utilizing the @Mapping
annotation, we demonstrated a straightforward approach to handle date conversions.
6. Download the Source Code
This was a guide on converting a String to Date using Java MapStruct.
You can download the full source code of this example here: java mapstruct string to date