英文:
MapStruct : Setting value of now while mapping?
问题
I am trying to set a DateTime field in my mapped classes using MapStruct, but could not see any example.
So, can I set a DateTime or Instant field value as now()
while mapping from DTO to Entity? How can I do this? I tried something below:
@Mapper(componentModel = "spring", imports = {Instant.class})
public interface DemoMapper {
@Mapping(source = "created", target = "created", defaultValue = Instant.now())
Employee toEntity(EmployeeDto source);
EmployeeDto toDto(Employee destination);
}
英文:
I am trying to set a DateTime field in my mapped classes using MapStruct, but could not see any example.
So, can I set a DateTime or Instant field value as now()
while mapping from DTO to Entity? How can I do this? I tried something below:
@Mapper(componentModel = "spring", imports = {Instant.class})
public interface DemoMapper {
@Mapping(source = "created", target = "created", defaultValue = Instant.now())
Employee toEntity(EmployeeDto source);
EmployeeDto toDto(Employee destination);
}
答案1
得分: 2
你可以在映射中使用defaultExpression
。它期望一个字符串作为参数,格式如下:
"java(expression)"
其中expression
是您要查找的表达式,所以在您的情况下:
@Mapping(source = "created", target = "created", defaultExpression = "java(java.time.Instant.now())")
请注意,我在Instant
类的全限定名称中使用了完全限定名称,因为defaultExpression
无法知道Instant
在哪里(或者至少不能假设您想要标准库中的Instant
),因此它不能在生成的文件中导入它。
英文:
You can use defaultExpression
in your mapping. It expects a string as an argument, with the following format:
"java(expression)"
Where expression
is the expression you're looking for, so in your case
@Mapping(source = "created", target = "created", defaultExpression = "java(java.time.Instant.now())")
Notice that I used the fully qualified name for the Instant
class, since defaultExpression
can't know where Instant
is (or at least it can't assume you want the one from the standard library), so it can't import it in the file it generates.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论