Continuation of the last time 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
}
Specify which bean field to use in the @Mapping
source attribute.
@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
Add @MappingTarget
to the argument to be updated.
@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
You can define a default method and add your own mapping method.
@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;
}
}
It has been created in the interface class so far, but it can also be created in the abstract class.
@Mapper
public abstract class FooBarMapper {
public Bar fooToBar(Foo foo) {
Bar bar = new Bar();
bar.setBar1(foo.getFoo1());
bar.setBar2(foo.getFoo2());
return bar;
}
}
When using it, it is necessary to explicitly create an instance.
FooBarMapperImpl mapper = new FooBarMapperImpl();
Bar bar = mapper.fooToBar(new Foo("AIUEO", "Kakikukeko"));
System.out.println(bar.getBar1()); //AIUEO
System.out.println(bar.getBar2()); //Kakikukeko
Next time.
Recommended Posts