Spring Boot 模型Map程序在dto到实体转换期间将值填充到错误的字段

knsnq2tg  于 2023-03-29  发布在  Spring
关注(0)|答案(1)|浏览(127)

我有一个名为MasterEntity的实体,它与另一个名为ChildEntity的实体有一个单向的一对一关系,按照下面的描述,这些实体被Map到相应的数据库表。

@Entity(name = "MasterEntity")
    @Data
    @AllArgsConstructor
    @NoArgsConstructor
    public class MasterEntity {
 
        @id
        private Integer Id;
        private String Name;
        private String Division;

        @OneToOne
        @MapsId
        @JoinColumn(name = "Id")
        private ChildEntity childEntity;

    }

    @Entity(name = "childEntity")
    @Data
    @AllArgsConstructor
    @NoArgsConstructor
    public class ChildEntity {
 
        @id
        private Integer Id;
        private String MatchingName;

    }

我有一个MasterEntityDTO,它包含以下字段。

@Builder
    @Data
    @AllArgsConstructor
    @NoArgsConstructor
    public class MasterEntityDTO {
 
    private Integer Id;
    private String Name;
    private String Division;

    }

我尝试使用Model Mapper将dto对象Map到Entity。由于我计划向Map到childEntity的DTO添加其他字段,因此将匹配策略设置为LOOSE

masterEntityDTO.setName("Jonathan");

    ModelMapper modelMapper = new ModelMapper();
    modelMapper.getConfiguration().setMatchingStrategy(MatchingStrategies.LOOSE);

    modelMapper.map(masterEntityDTO, MasterEntity.class);

我得到的结果实体具有以下值。

Id = null
Name = "Jonathan"
Division = null
Id = null
MatchingName = "Jonathan"

所以我的字段MatchingName被错误地填充为Name字段的值。
我尝试了modelMapper的不同配置,但这并没有解决问题。我该如何解决这个问题?

s4n0splo

s4n0splo1#

如ModelMapper文档中处理不匹配部分所述:
虽然ModelMapper会尽最大努力隐式地为您匹配源属性和目标属性,但有时您可能需要显式地定义属性之间的Map。
ModelMapper支持多种Map方法,允许您混合使用方法和字段引用。
因此,在本例中,您需要定义自定义Map。
或者你需要使用MatchingStrategies.Standard,而不是Loose。

相关问题