Mapstruct如何初始化字段
Mapstruct how to initialize fields
我有一个这样的 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);
}
当有源但解析时源为空时,defaultExpression
可以方便地为目标赋值。
我有一个这样的 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);
}
当有源但解析时源为空时,defaultExpression
可以方便地为目标赋值。