繁体   English   中英

如何忽略一个 class 中另一个 class 的任何字段?

[英]How can I ignore any field of another class within one class?

我的意思是,例如,我有 ProductDTO 和 OrderDetail 类。 我想忽略 json 上的价格字段,因为价格是可变的,我想保持购买价格。 这是我的 ProductDTO:

public class ProductDTO {

    String id;
    String name;
    String description;
    int price; //I want to ignore this one
    String brand;
    String size;
    int stockCount;
    String type;
    String color;
    String gender;
}

这是我的 OrderDetail class:

public class OrderDetail {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    Long id;
    int price;
    ProductDTO productDTO;
}

首先,我们从未在 integer 中标价,它是双精度或大十进制。 其次,我们从不在实体中放置 DTO。 DTO 是一种允许数据传输而不影响实体的设计模式。

对于您的问题,它是 DTO 和实体之间的简单映射点。 通过手动方法实现或使用映射器生成的代码(如 MapStruct)来使用映射器。

例如,您想忽略这样的价格:

@Mapper(componentModel = "spring")
public interface ProductMapper {
    
    @Mappings({
        @Mapping(source = "idDTO", target = "id"),
        @Mapping(source = "price", target = "price", ignore = true),
        @Mapping(source = "idArriveePar", target = "idArrivePar"),
    })
    Product toEntity(ProductDTO productDTO);
}

这将忽略您想要的价格。

希望这会有所帮助

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM