Skip to content
Advertisement

Mapstruct how to initialize fields

I have a DTO like this

@Data
public class MessageDTO implements Serializable {
    private Long id;
}

and an entity

@Entity
@Data
public class Message implements Serializable {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name = "id")
    private Long id;

    @Column(name = "timestamp")
    private Instant timestamp;
}

I want to create a mapper to map DTO to entity. How can I make the field private Instant timestamp; has value like Instant.now()?

My mapper so far

@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);
}

It got compile error

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)

Advertisement

Answer

The issue is due to the source being empty. Remove the source and use expression instead of defaultExpression.

@Mapper(componentModel = "spring")
public interface MessageMapper extends EntityMapper<MessageDTO, Message> {
    @Override
    @Mapping(target = "timestamp", expression = "java(Instant.now())")
    Message toEntity(MessageDTO dto);
}

When there is a source but the source is null upon resolving, then defaultExpression comes handy to assign a value to the target.

User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement