通過this answer啓發映射不變對象的集合,我已經寫了一個定製conveter(你可以找到在Github repo整個工作示例)。對於推土機轉換之間:如何推土機
public class MyEntity {
private List<ObjectId> attachmentIds;
public List<ObjectId> getAttachmentIds() { return attachmentIds; }
public void setAttachmentIds(List<ObjectId> attachmentIds) {
this.attachmentIds = attachmentIds;
}
}
而其DTO:
public class MyEntityDto {
private List<FileDataDto> attachments;
public List<FileDataDto> getAttachments() { return attachments; }
public void setAttachments(List<FileDataDto> attachments) {
this.attachments = attachments;
}
}
MyEntity
只保存存儲在蒙戈DATABSE文件的ID。它的DTO被髮送到JSON的前端,應該包含id和文件的文件名(這是FileDataDto
類的內容)。我的轉換器:
public class FileIdToFileDataConverter extends DozerConverter<ObjectId, FileDataDto> {
public FileIdToFileDataConverter() {super(ObjectId.class, FileDataDto.class); }
@Override
public FileDataDto convertTo(ObjectId source, FileDataDto destination) {
if (source == null) {
return null;
}
FileDataDto fileData = destination == null ? new FileDataDto() : destination;
fileData.setId(source.toString());
// fetch the file from repository and update the name from db
fileData.setFilename("myfile.txt");
return fileData;
}
@Override
public ObjectId convertFrom(FileDataDto source, ObjectId destination) {
return source == null ? null : new ObjectId(source.getId());
}
}
改建工程預期在MyEntity
- >MyEntityDto
方向。然而,它卻在相反的情況下失敗。它使用Dozer創建的ObjectId
(作爲destination
參數傳遞)而不是轉換器返回的那個。這個測試
@Test
public void dtoToMyEntity() {
MyEntityDto dto = new MyEntityDto();
FileDataDto fileData = new FileDataDto();
fileData.setFilename("file.txt");
fileData.setId(new ObjectId().toString());
dto.setAttachments(Arrays.asList(fileData));
MyEntity myEntity = mapper.map(dto, MyEntity.class);
assertEquals(fileData.getId(), myEntity.getAttachmentIds().get(0).toString());
}
用一個例子消息失敗:
org.junit.ComparisonFailure:
Expected :56b0a9d110a937fc32a6db18
Actual :56b0a9d110a937fc32a6db19
你可以找到整個測試和配置我在Github repo使用。
如何使這兩種方式的轉換器的工作?