Object Factoryを使って、マッピングするオブジェクトを生成することができる。
環境
Object Factoryの作成
public class StudentFactory { public Student createStudent() { Student student = new Student(); student.setAddress("STUDENT_FACTORY"); return student; } }
Mapperの作成
@Mapper
にFactoryクラスを指定する。
@Mapper(uses = StudentFactory.class) public interface StudentMapper { StudentMapper MAPPER = Mappers.getMapper(StudentMapper.class); @Mapping(target = "address", ignore = true) Student toStudent(StudentEntity entity); }
生成されたコード
/* @Generated( value = "org.mapstruct.ap.MappingProcessor", date = "2018-03-18T14:54:28+0900", comments = "version: 1.2.0.Final, compiler: javac, environment: Java 9.0.1 (Oracle Corporation)" ) */ public class StudentMapperImpl implements StudentMapper { private final StudentFactory studentFactory = new StudentFactory(); @Override public Student toStudent(StudentEntity entity) { if ( entity == null ) { return null; } Student student = studentFactory.createStudent(); student.setName( entity.getName() ); student.setAge( entity.getAge() ); return student; } }
テストコード
@Test public void test() { StudentEntity entity = new StudentEntity(); Student student = StudentMapper.MAPPER.toStudent(entity); assertThat(student.getAddress()).isEqualTo("STUDENT_FACTORY"); }