我有一个类似的DTO
@Data
public class MessageDTO implements Serializable {
private Long id;
}
和一个实体
@Entity
@Data
public class Message implements Serializable {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "id")
private Long id;
@Column(name = "timestamp")
private Instant timestamp;
}
我想创建一个映射器来将DTO映射到实体。如何使字段private Instant timestamp;
具有Instant.now((这样的值?
到目前为止我的映射器
@Mapper(componentModel = "spring", imports = Instant.class)
public interface MessageMapper extends EntityMapper<MessageDTO, Message> {
@Override
@Mapping(target = "timestamp", source = "" ,defaultExpression = "java(Instant.now())")
Message toEntity(MessageDTO dto);
}
它得到了编译错误
Compilation failure
[ERROR] /D:/Shared/projects/IdeaProjects/medical/src/main/java/io/medical/service/mapper/MessageMapper.java:[22,45] No property named "" exists in source parameter(s)
问题是由于source
为空。移除source
并使用expression
而不是defaultExpression
。
@Mapper(componentModel = "spring")
public interface MessageMapper extends EntityMapper<MessageDTO, Message> {
@Override
@Mapping(target = "timestamp", expression = "java(Instant.now())")
Message toEntity(MessageDTO dto);
}
如果存在源,但解析时源为null,则defaultExpression
可以方便地为目标分配值。