Fortsetzung des letzten Males http://qiita.com/kentama/items/09a8573bd5d0831b470e
Bean
public class Hoge {
private String hoge1;
private String hoge2;
private String hoge3;
private String hoge4;
// constructor/getter/setter
}
public class Fuga {
public String fuga1;
public String fuga2;
// constructor/getter/setter
}
public class Piyo {
public String piyo1;
public String piyo2;
// constructor/getter/setter
}
Das Quellattribut @ Mapping
gibt an, welches Bean-Feld verwendet werden soll.
@Mapper
public interface HogeMapper {
HogeMapper INSTANCE = Mappers.getMapper(HogeMapper.class);
@Mapping(target = "hoge1", source = "fuga.fuga1")
@Mapping(target = "hoge2", source = "fuga.fuga2")
@Mapping(target = "hoge3", source = "piyo.piyo1")
@Mapping(target = "hoge4", source = "piyo.piyo2")
public Hoge map(Fuga fuga, Piyo piyo);
}
Fuga fuga = new Fuga("a", "b");
Piyo piyo = new Piyo("c", "d");
Hoge hoge = HogeMapper.INSTANCE.map(fuga, piyo);
System.out.println(hoge.getHoge1()); // a
System.out.println(hoge.getHoge2()); // b
System.out.println(hoge.getHoge3()); // c
System.out.println(hoge.getHoge4()); // d
Fügen Sie dem zu aktualisierenden Argument "@ MappingTarget" hinzu.
@Mapper
public interface UpdateMapper {
UpdateMapper INSTANCE = Mappers.getMapper(UpdateMapper.class);
@Mapping(target = "hoge1", source = "fuga1")
@Mapping(target = "hoge2", source = "fuga2")
@Mapping(target = "hoge3", source = "fuga1")
@Mapping(target = "hoge4", source = "fuga2")
public void updateHogeFromFuga(Fuga fuga, @MappingTarget Hoge hoge);
}
Fuga fuga = new Fuga("a", "b");
Hoge hoge = new Hoge("1", "2", "3", "4");
UpdateMapper.INSTANCE.updateHogeFromFuga(fuga, hoge);
System.out.println(hoge.getHoge1()); // a
System.out.println(hoge.getHoge2()); // b
System.out.println(hoge.getHoge3()); // a
System.out.println(hoge.getHoge4()); // b
Sie können eine Standardmethode definieren und Ihre eigene Zuordnungsmethode hinzufügen.
@Mapper
public interface FooBarMapper {
FooBarMapper INSTANCE = Mappers.getMapper(FooBarMapper.class);
default Bar fooToBar(Foo foo) {
Bar bar = new Bar();
bar.setBar1(foo.getFoo1());
bar.setBar2(foo.getFoo2());
return bar;
}
}
Es wurde bisher in der Interface-Klasse erstellt, kann aber auch in der abstrakten Klasse erstellt werden.
@Mapper
public abstract class FooBarMapper {
public Bar fooToBar(Foo foo) {
Bar bar = new Bar();
bar.setBar1(foo.getFoo1());
bar.setBar2(foo.getFoo2());
return bar;
}
}
Bei der Verwendung muss explizit eine Instanz erstellt werden.
FooBarMapperImpl mapper = new FooBarMapperImpl();
Bar bar = mapper.fooToBar(new Foo("AIUEO", "Kakikukeko"));
System.out.println(bar.getBar1()); //AIUEO
System.out.println(bar.getBar2()); //Kakikukeko
Nächstes Mal.
Recommended Posts