Use MapStruct 1.1.0
See the official website for details on MapStruct http://mapstruct.org/
Bean
public class ProfileForm {
private String name;
private int age;
private String location;
// constructor/getter/setter
}
public class Profile {
private String name;
private int age;
private String location;
// constructor/getter/setter
}
@Mapper
public interface ProfileMapper {
ProfileMapper INSTANCE = Mappers.getMapper(ProfileMapper.class);
public Profile profileFormToProfile(ProfileForm form);
}
ProfileForm form = new ProfileForm("Michael scofield", 30, "United States of America");
Profile profile = ProfileMapper.INSTANCE.profileFormToProfile(form);
System.out.println(profile.getName()); //Michael scofield
System.out.println(profile.getAge()); // 30
System.out.println(profile.getLocation()); //United States of America
To exclude a part of the field from the mapping target, use the @Mapping
annotation.
Set the field to be excluded in the target attribute and true
in the ignore attribute.
@Mapper
public interface ProfileMapper {
ProfileMapper INSTANCE = Mappers.getMapper(ProfileMapper.class);
@Mapping(target = "name", ignore = true)
public Profile profileFormToProfile(ProfileForm form);
}
@Mapper
public interface ProfileMapper {
ProfileMapper INSTANCE = Mappers.getMapper(ProfileMapper.class);
public Profile profileFormToProfile(ProfileForm form);
//add to
public List<Profile> profileFormToProfile(List<ProfileForm> forms);
}
List<ProfileForm> forms = Arrays.asList(new ProfileForm("Michael scofield", 30, "United States of America")
, new ProfileForm("Lincoln Burrows", 34, "United States of America"));
List<Profile> profiles = ProfileMapper.INSTANCE.profileFormToProfile(forms);
System.out.println(profiles.get(1).getName()); //Lincoln Burrows
System.out.println(profiles.get(1).getAge()); // 34
System.out.println(profiles.get(1).getLocation()); //United States of America
Bean
public class Foo {
private String foo1;
private String foo2;
// constructor/getter/setter
}
public class Bar {
private String bar1;
private String bar2;
// constructor/getter/setter
}
@Mapper
public interface FooBarMapper {
FooBarMapper INSTANCE = Mappers.getMapper(FooBarMapper.class);
@Mapping(target = "bar1", source = "foo1")
@Mapping(target = "bar2", source = "foo2")
public Bar fooToBar(Foo foo);
}
Specify the field (target) to be mapped and the field (source) to be mapped with the @Mapping
annotation.
Foo foo = new Foo("AIUEO", "Kakikukeko");
Bar bar = FooBarMapper.INSTANCE.fooToBar(foo);
System.out.println(bar.getBar1()); //AIUEO
System.out.println(bar.getBar2()); //Kakikukeko
There are other features for mapping, but they will be next time.
Recommended Posts