【问题标题】:Map abstract class to DTO with MapStruct使用 MapStruct 将抽象类映射到 DTO
【发布时间】:2020-07-07 03:36:07
【问题描述】:

我发现了很多关于这个的话题,但所有的解决方案在我看来都走错了方向。

那么...我如何在这种情况下使用 MapStruct 映射?

抽象类人:

public abstract class Person implements Serializable{

     private String name;
     private String somethingToIgnore

     //Getter and Setter

}

普通的 Mapper 不起作用:

@Mapper(componentModel = 'cdi')
public interface PersonMapper{

    @Mapping(target = 'somethingToIgnore', ignore = 'true')
    Person toPerson(PersonDTO source);

    @InheritInverseConfiguration
    PersonDTO toPersonDtO(Person source);

}

我不允许映射抽象类。我应该使用工厂方法。我试过了,但我根本不知道这个工厂方法应该是什么样子......

我的尝试:

@Mapper
public interface PersonMapper {

    PersonMapper INSTANCE = Mappers.getMapper( PersonMapper.class );

    Person toPerson(PersonDTO source);

    PersonDTO toPersonDtO(Person source);
}

@Mapper
public abstract class PersonMapper {

    public static final PersonMapper INSTANCE = Mappers.getMapper( PersonMapper.class );

    Person toPerson(PersonDTO source);

    PersonDTO toPersonDtO(Person source);
}

我错过了什么,做错了什么? 提前致谢。

【问题讨论】:

    标签: java mapping dto mapstruct java-ee-8


    【解决方案1】:

    MapStruct 不知道如何映射到抽象类,因为它无法实例化它。我希望你有一些Person 的实现。您需要提供将创建 Person 对象的方法,如下所示:

    @Mapper
    public interface PersonMapper {
    
        Person toPerson(PersonDTO source);
    
        PersonDTO toPersonDtO(Person source);
    
        default Person createPerson() {
            return new PersonImpl();
        }
    }
    

    这样 MapStruct 将使用此方法创建Person 实例,而不是像往常一样映射属性。你可以在the documentation找到更多关于对象工厂的信息。

    【讨论】:

    • 我又犯了一个可怕的错误。您的回答已经在帮助我。我将在下周对其进行测试并报告。 ty
    • 我又犯了一个错误..我的问题确实正确,但无论如何我会标记你回答正确,因为它是正确的。
    • @Julien,我想到的一种方法是使用@Context。像这样的东西:Person toPerson(PersonDTO source, @Context PersonDTO context);default Person createPerson(@Context PersonDTO context)
    • @Julien,如果你不想把同一个对象作为参数两次,你可以像这样重载toPerson方法:default Person toPerson(PersonDTO source) { return toPerson(source, source); }
    • @Tuom 谢谢。我刚刚通过升级 mapstruct 版本找到了解决方案,然后使用 \@ObjectFactory default Person toPerson(PersonDTO source) {...}
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2023-03-23
    • 2021-11-28
    • 2017-09-17
    • 1970-01-01
    • 2020-09-20
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多