【发布时间】:2016-02-02 13:18:39
【问题描述】:
受this answer 的启发,我编写了一个自定义转换器(您可以在Github repo 中找到整个工作示例)。用于 Dozer 之间的转换:
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 仅保存存储在 Mongo 数据库中的文件的 ID。它以 JSON 格式发送到前端的 DTO 应该包含文件的 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 中找到我使用的整个测试和配置。
如何让转换器双向工作?
【问题讨论】:
标签: java immutability dozer