如何使用仅原始属性作为源的 MapStruct?

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

我有以下对象:

@Value
public class CompanyDto {
    int id;
    int accountId;
}

我尝试使用

MapStruct
(版本
1.5.2.Final
将两个原始属性映射到新的
CompanyDto
对象:

@Mapper
public interface CompanyMapper {

    CompanyDto mapToDto(int id, int accountId);
}

我遇到编译错误:

错误:表达式非法开始

    if (  ) {
          ^

所以我看到

MapStruct
尝试检查某些东西的
null
值,但没有任何对象可以检查
null
并且它生成空的
if
条件,这是导致编译错误的原因。

这是错误还是我做错了什么?

java mapstruct
1个回答
0
投票

即使我认为解决您的问题有点晚了,但它可能会帮助其他用户。 Mapstruct 试图验证不同字段的可空性,通常给定的类型是对象。就您而言,您正在使用原始类型。 所以生成器无法检查空值。 该解决方案通过使用包装类(Integer 而不是 int) 这样代码就会正确生成:

import org.mapstruct.Mapper;
 @Mapper
 public interface CompanyMapper {
 CompanyDto mapToDto(Integer id, Integer accountId);
 }

这实际上会产生这个:

import javax.annotation.processing.Generated;

@Generated(
value = "org.mapstruct.ap.MappingProcessor",
date = "2024-10-11T13:08:19+0200",
comments = "version: 1.5.3.Final, compiler: javac, environment: Java 17.0.6 (Eclipse Adoptium)"
)
public class CompanyMapperImpl implements CompanyMapper {

@Override
public CompanyDto mapToDto(Integer id, Integer accountId) {
    if ( id == null && accountId == null ) {
        return null;
    }

    int id1 = 0;
    if ( id != null ) {
        id1 = id;
    }
    int accountId1 = 0;
    if ( accountId != null ) {
        accountId1 = accountId;
    }

    CompanyDto companyDto = new CompanyDto( id1, accountId1 );

    return companyDto;
}
}

希望对您有帮助:)

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