MapStruct: 在映射时设置”now”的值?

huangapple go评论69阅读模式
英文:

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.

huangapple
  • 本文由 发表于 2023年2月26日 19:58:05
  • 转载请务必保留本文链接:https://go.coder-hub.com/75571815.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定