如何在 Java 中使用 MapStruct 將字串轉換為日期?
一、簡介
MapStruct是Java中一個功能強大的函式庫,它簡化了編譯時不同物件模型之間映射的過程。它使用註釋自動生成類型安全的映射器實現,使其高效且易於維護。
MapStruct 通常用於需要物件到物件映射的應用程序,例如在層之間傳輸資料或將 DTO 轉換為實體。一個常見的用例是將String轉換為Date對象,由於日期格式和解析要求眾多,這個過程可能很棘手。在本文中,我們將探索使用 MapStruct 實現此轉換的各種方法。
2. 依賴關係
要開始使用 MapStruct,我們必須在專案中包含必要的依賴項。對於 Maven 項目,我們將以下相依性新增至pom.xml中:
<dependency>
<groupId>org.mapstruct</groupId>
<artifactId>mapstruct</artifactId>
<version>1.5.5.Final</version>
</dependency>
此外,我們配置[maven-compiler-plugin](https://mvnrepository.com/artifact/org.apache.maven.plugins/maven-compiler-plugin)以包含 MapStruct處理器:
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.13.0</version>
<configuration>
<annotationProcessorPaths>
<path>
<groupId>org.mapstruct</groupId>
<artifactId>mapstruct-processor</artifactId>
<version>1.5.5.Final</version>
</path>
</annotationProcessorPaths>
</configuration>
</plugin>
</plugins>
</build>
設定完這些依賴項後,我們就可以開始在專案中使用 MapStruct 了。
3. 使用@Mapping註解進行基本映射
MapStruct 提供@Mapping註釋來定義一種類型中的屬性應如何對應到另一種類型。預設情況下,MapStruct 不支援String和Date之間的直接轉換。但是,我們可以利用@Mapping註解的format屬性來處理轉換。
讓我們來看一個基本範例,其中將UserDto對應到User實體:
public class UserDto {
private String name;
// Date in String format
private String birthDate;
// getters and setters
}
public class User {
private String name;
private Date birthDate;
// getters and setters
}
@Mapper
public interface UserMapper {
@Mapping(source = "birthDate", target = "birthDate", dateFormat = "yyyy-MM-dd")
User toUser(UserDto userDto);
}
在此範例中, @Mapping註解指定UserDto中的birthDate欄位應對應到User中的birthDate欄位。 dateFormat屬性用於定義日期字串的格式,允許 MapStruct 自動處理轉換。
讓我們驗證一下這個轉換:
@Test
public void whenMappingUserDtoToUser_thenMapsBirthDateCorrectly() throws ParseException {
UserDto userDto = new UserDto();
userDto.setName("John Doe");
userDto.setBirthDate("2024-08-01");
User user = userMapper.toUser(userDto);
assertNotNull(user);
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
Date expectedDate = dateFormat.parse("2024-08-01");
Assertions.assertEquals(expectedDate, user.getBirthDate());
}
在此測試案例中,我們使用UserMapper確認birthDate從UserDto到User準確映射,從而確認預期的日期轉換。
4. 實作自訂轉換方法
有時,我們可能需要為更複雜的場景實作自訂轉換方法。這些方法可以直接在映射器介面中定義。透過使用@Mapping註解的expression屬性,我們可以指示 MapStruct 使用我們的自訂轉換方法.
以下是我們如何定義將String轉換為Date自訂方法:
@Mapper
public interface UserMapper {
@Mapping(target = "birthDate", expression = "java(mapStringToDate(userDto.getBirthDate()))")
User toUserCustom(UserDto userDto) throws ParseException;
default Date mapStringToDate(String date) throws ParseException {
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
return dateFormat.parse(date);
}
}
在此範例中, mapStringToDate()方法使用SimpleDateFormat將String轉換為Date 。我們在@Mapping註解中使用明確表達式來告訴 MapStruct 在映射期間呼叫此方法。
5. 重複使用通用自訂方法
假設我們的專案中有多個需要相同類型轉換的映射器。在這種情況下,在單獨的實用程式類別中定義自訂映射方法並在不同的映射器之間重複使用它們會更有效。
首先,我們將使用轉換方法建立一個實用程式類別:
public class DateMapper {
public Date mapStringToDate(String date) throws ParseException {
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
return dateFormat.parse(date);
}
}
然後,讓我們在映射器中使用這個實用程式類別:
@Mapper(uses = DateMapper.class)
public interface UserConversionMapper {
@Mapping(source = "birthDate", target = "birthDate")
User toUser(UserDto userDto);
}
透過在@Mapper註解中指定uses = DateMapper.class ,我們告訴MapStruct使用DateMapper中的方法進行轉換。這種方法促進了程式碼重用並保持我們的映射邏輯的組織性和可維護性。
六、結論
MapStruct 是 Java 中物件到物件映射的強大工具。透過利用自訂方法,我們可以輕鬆處理不支援開箱即用的類型轉換,例如將String轉換為Date 。
透過遵循本文中概述的步驟,我們可以在專案中有效地實現和重複使用自訂轉換方法。此外,在@Mapping註解中使用dateFormat屬性可以簡化直接日期轉換的過程。
這些技術使我們能夠充分利用 MapStruct 的潛力來實現 Java 應用程式中的各種映射場景。
與往常一樣,原始碼可以在 GitHub 上取得。