问题
springboot
在使用mapstruct
对对象进行转换时遇到一个问题,即在对象使用了@SuperBuilder
注解时mapstruct生成的转换类会报错(Mapper放在涉及转换的类内,另外写class不会报错),报错如下
@Data
@SuperBuilder(toBuilder = true)
@AllArgsConstructor
@NoArgsConstructor
public class TestSuperClass {
private String column1;
private String column2;
}
@EqualsAndHashCode(callSuper = true)
@Data
@SuperBuilder(toBuilder = true)
@AllArgsConstructor
@NoArgsConstructor
public class TestClass extends TestSuperClass{
private String column3;
private String column4;
@Mapper(unmappedTargetPolicy = ReportingPolicy.IGNORE)
public interface TestClassModelMapper {
TestTargetClass doToTarget(TestClass testClass);
}
public static final TestClassModelMapper INSTANCE = Mappers.getMapper(TestClassModelMapper.class);
}
@Data
@Builder
@AllArgsConstructor
@NoArgsConstructor
public class TestTargetClass {
private String column1;
private String column2;
private String column3;
private String column4;
}
以上为各实体类
@Generated(
value = "org.mapstruct.ap.MappingProcessor",
date = "2021-07-06T15:28:32+0800",
comments = "version: 1.4.2.Final, compiler: javac, environment: Java 1.8.0_251 (Oracle Corporation)"
)
public class TestClass$TestClassModelMapperImpl implements TestClassModelMapper {
@Override
public TestTargetClass doToTarget(TestClass testClass) {
if ( testClass == null ) {
return null;
}
TestTargetClassBuilder testTargetClass = TestTargetClass.builder();
testTargetClass.column1( testClass.getColumn1() );
testTargetClass.column2( testClass.getColumn2() );
testTargetClass.column3( testClass.getColumn3() );
testTargetClass.column4( testClass.getColumn4() );
return testTargetClass.build();
}
@Override
public TestClass doToDo(TestClass testClass) {
if ( testClass == null ) {
return null;
}
TestSuperClassBuilder<?, ?> testClass1 = TestSuperClass.builder();
testClass1.column1( testClass.getColumn1() );
testClass1.column2( testClass.getColumn2() );
return testClass1.build();
}
}
以上为mapstruct生成的转换class,很明显生成的转换类内调用了父类的Builder
导致返回类型错误
解决方案
在TestClass
内部Mapper的注解@Mapper
内添加参数builder = @Builder(disableBuilder = true)
,即
@EqualsAndHashCode(callSuper = true)
@Data
@SuperBuilder(toBuilder = true)
@AllArgsConstructor
@NoArgsConstructor
public class TestClass extends TestSuperClass implements Serializable {
private static final long serialVersionUID = 1L;
private String column3;
private String column4;
@Mapper(unmappedTargetPolicy = ReportingPolicy.IGNORE, builder = @Builder(disableBuilder = true))
public interface TestClassModelMapper {
TestTargetClass doToTarget(TestClass testClass);
TestClass doToDo(TestClass testClass);
}
public static TestClass.TestClassModelMapper INSTANCE = Mappers.getMapper(TestClass.TestClassModelMapper.class);
}