转换对象的类型

问题描述 投票:0回答:1

这是我的实体:

@Getter
@Setter
@Entity
@Inheritance(strategy = InheritanceType.SINGLE_TABLE)
@DiscriminatorColumn(name = "dtype", discriminatorType = DiscriminatorType.STRING, columnDefinition = "varchar(31) default 'RAW_QUOTATION'")
public class Quotations {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;
    private String description;
}

我想将其所有属性扩展到以下内容:

@Getter
@Setter
public class SingleQuotationDto extends Quotations {
    private String receiverName;
}

在我的服务中,我有一个类型为

Quotations
:

的对象
Optional<Quotations> quotation = quotationRepository.findById(id);
    quotation.ifPresent(quotations -> {
...
}

我想把这个对象的类型转换成

SingleQuotationDto
,这样我就可以给它设置
receiverName

我知道我能做到:

SingleQuotationDto singleQuotationDto = new SingleQuotationDto(quotations);
singleQuotationDto.setReceiverName("Receiver's Name");
singleQuotationDto.setDescription("description");

但是

quotations
已经是预定义的。所以我不想手动添加每个属性。

此外,如果我对实体使用 setter,我认为这是一种不好的做法。因为当我添加新属性时,我也必须在此服务中添加它们的设置器。我很确定必须有一个更清洁的解决方案。

java spring-boot
1个回答
0
投票

解决方案是注释

@delegate
(lombok.experimental.Delegate) 以及
@JsonIgnore
(com.fasterxml.jackson.annotation.JsonIgnore;) 以避免重复的属性。

@Getter
@Setter
public class SingleQuotationDto {
    @Delegate
    @JsonIgnore
    private Quotations quotations;
    private String receiverName;
}
SingleQuotationDto singleQuotationDto = new SingleQuotationDto();
singleQuotationDto.setQuotations(quotations);
singleQuotationDto.setReceiverName("Receiver's Name");
© www.soinside.com 2019 - 2024. All rights reserved.