java设置LocalDateTime的值。使用ModelMapper进行映射时,将now()转换为两个字段
我必须通过ModelMapper将从UI获取的数据映射到实体
在使用ModelMapper之前,我有以下方法:
private Operation map(OperationForm src) {
Operation operation = new Operation();
LocalDateTime NOW = LocalDateTime.now();
operation.setOperationKey(OperationKey.of(src.getLegalEntityId(),
src.getEmployeeId(),
NOW)); // here
operation.setIndividualId(src.getIndividualId());
operation.setKey(src.getLegalEntityId() + "_"
+ src.getEmployeeId() + "_"
+ NOW); // and here
return operation;
}
在这种情况下,我必须通过LocalDateTime生成新的LocalDateTime。现在()和在两个不同的字段中使用它强>
所以,我尝试这样配置ModelMapper:
public OperationFormMapper(ModelMapper modelMapper) {
Converter<OperationForm, OperationKey> operationKeyConverter = (context) -> OperationKey.of(context.getSource().getLegalEntityId(),
context.getSource().getEmployeeId(),
LocalDateTime.now()); // generate new LocalDateTime to
// destination instance
Converter<Operation, String> keyConverter = (context) -> {
Operation src = context.getSource();
return src.getOperationKey().getLegalEntityId() + "_"
+ src.getOperationKey().getEmployeeId() + "_"
+ src.getOperationKey().getOperationDate();
}; // converter for my purpose
// I am trying to get value not from source,
// but from destination instance, hoping that
// all needed fields are already mapped
this.modelMapper = modelMapper;
this.modelMapper.addMappings(new PropertyMap<OperationForm, Operation>() {
@Override
protected void configure() {
using(operationKeyConverter).map(source, destination.getOperationKey());
map().setIndividualId(source.getIndividualId());
map().setOperationStatus(Operation.OperationStatus.CREATED);
using(keyConverter).map(destination, destination.getKey());
// trying to get all needed data from already mapped fields
}
});
}
它不起作用并不奇怪。我得到了NullPointerException。显然,在我试图获取关键字段的值时,字段仍然没有映射
那么,有人知道如何处理这一时刻,并使ModelMapper也适用于我的情况吗?或者至少有一些方法可以完全定制映射过程并创建ModelMapper用于映射的整个方法(或者使用上面已有的方法)
更新:
我的实体:
public class Operation {
private OperationKey operationKey;
private Long individualId;
private String operationStatus;
private String operationResult;
private String guardCardSeries;
private String guardCardNumber;
private LocalDateTime guardCardStartDate;
private LocalDateTime guardCardEndDate;
private String resultMessage;
private String key;
}
用户界面中的我的DTO:
public class OperationForm implements Serializable {
private Long legalEntityId;
private Long employeeId;
private Long individualId;
}
我的Cassandra DB复合密钥:
public class OperationKey {
private final Long legalEntityId;
private final Long employeeId;
private final LocalDateTime operationDate;
}
我只是通过删除持久性注释简化了它们
# 1 楼答案
看来我找到了解决办法
现在是ModelMapper的配置
我创建了Converter并将我的方法引入其中。现在它起作用了