摘要: MapStruct更擅长的是处理特殊情形下的java bean间转换,如Java中的枚举Enum类型转换。在学习了MapStruct简单使用方法之后,可以探索更复杂的业务情形。
有一个User对象,其属性等级(grade)是一个枚举类型:
public class User {
public enum Grade{
AVERAGE,BRONZE,GOLD,DIAMOND;
}
private Grade grade;
// setters, getters, toString()
}
有一个UserDao对象,其属性等级(level)是一个枚举类型:
public class UserDao {
public enum Level{
AVERAGE,BRONZE,GOLD,DIAMOND;
}
private Level level;
// setters, getters, toString()
}
将User转换为UserDao,两个实体的枚举值相同,名称不同,只需要配置映射关系即可。
@Mapper
public interface UserMapper {
UserMapper INSTANCE = Mappers.getMapper(UserMapper.class);
@Mappings({
@Mapping(source="grade", target="level")
})
UserDao userToUserDao(User user);
}
@Test
public void test1(){
User user = new User();
user.setGrade(Grade.DIAMOND);
UserDao e = UserMapper.INSTANCE.userToUserDao(user);
System.out.println(e);
}
结果:
UserDao [level=DIAMOND]
简单的枚举转换不需要太多配置,MapStrut能自动地处理Enum类型。
有一个UserDojo对象,其属性等级(grade)是一个枚举类型:
public class UserDojo {
public enum RANK{
NORMAL,JUNIOR,SENIOR,MASTER;
}
private RANK rank;
// setters, getters, toString()
}
将User转换为UserDojo ,两个实体的枚举值存在对应关系,User的Grade类型AVERAGE,BRONZE,GOLD,DIAMOND分别对应UserDojo的RANK类型NORMAL,JUNIOR,SENIOR,MASTER。
@Mapper
public interface UserMapper {
UserMapper INSTANCE = Mappers.getMapper(UserMapper.class);
@Mappings({
@Mapping(source="grade", target="rank")
})
UserDojo userToUserDojo(User user);
@ValueMappings({
@ValueMapping(source="AVERAGE",target="NORMAL"),
@ValueMapping(source="BRONZE",target="JUNIOR"),
@ValueMapping(source="GOLD",target="SENIOR"),
@ValueMapping(source="DIAMOND",target="MASTER"),
@ValueMapping(source=MappingConstants.ANY_UNMAPPED, target=MappingConstants.NULL)
})
RANK customConveter(Grade grade);
}
@Test
public void test1(){
User user = new User();
user.setGrade(Grade.DIAMOND);
UserDojo u = UserMapper.INSTANCE.userToUserDojo(user);
System.out.println(u);
}
结果:
UserDojo [rank=MASTER]
自定义了customConverter()方法来映射Enum值,用到了@ValueMapping注解。最后一行还使用了MapStruct的常量,想要达到的效果是在映射失败时,默认值为null。
项目代码托管在码云。