我想将 Dto 类的多个字段映射到实体的单个字段,反之亦然。如何实现这一目标?

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

所以在这里, 我们有一个实体类 - Contact

public class Contact {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;
    @Column(name = "name",nullable = false)
    private String name;
    @Column(name = "email",nullable = false,unique = true)
    private String email;
    @Column(name = "phone",nullable = false)
    private String phone;
}

DTO 类 - ContactDto

public class ContactDto {
    private Long id;
    private String fname;
    private String lname;
    private String email;
    private String phone;
}

我想将 fname 和 lname 与联系人中的 name 属性映射,反之亦然。如何实现这个解决方案?

我尝试使用 MapStruct 库。我很困惑如何实现这个逻辑。请使用 MapStruct 或 ModelMapper 帮助我。

@Mapper
public interface ContactMapper {
    ContactMapper INSTANCE = Mappers.getMapper(ContactMapper.class);
    ContactDto mapToContactDto(Contact contact);
    Contact mapToContact(ContactDto contactDto);
}

这就是我尝试使用 Mapstruct 所做的。

java spring rest mapstruct modelmapper
1个回答
0
投票

我建议阅读这个问题。 如何将实体转换为 dto,反之亦然

如果您想继续使用 MapStruct 这里有很好的解释。 Baeldung - 地图结构

通常最好编写自己的映射器,因为你可以完全控制正在发生的事情,并且如果将来某些测试停止工作,你也不会那么头疼。

© www.soinside.com 2019 - 2024. All rights reserved.