【问题标题】:How can I ignore any field of another class within one class?如何忽略一个类中另一个类的任何字段?
【发布时间】:2021-03-25 21:58:14
【问题描述】:

我的意思是,例如,我有 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 类:

public class OrderDetail {

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

【问题讨论】:

    标签: java json spring-boot spring-data


    【解决方案1】:

    首先,我们从不以整数形式给出价格,它是 double 或 bigDecimal。 其次,我们从不将 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);
    }
    

    这将忽略你想要的价格。

    希望这会有所帮助

    【讨论】:

    • 首先,我们从不以整数定价。废话。我使用过许多 PoS 系统,其中价格以基本单位存储:美分、便士等。
    • 如果我们使用不同的货币?这仍然有效吗?以欧元为便士,但对于中国或日本货币来说,它更重要,与货币相比,外部化或在每种情况下扩大类别是否更公平......?我认为最好将正确的交易基础尽可能小
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-06-14
    • 1970-01-01
    • 2016-12-24
    • 1970-01-01
    相关资源
    最近更新 更多