在日常的开发中,为了避免污染直接映射数据库的java bean类,通过我们另写一个vo类并设置相关需要展示的属性。为了把值赋值到vo类,平常使用的方法有自己写get()与set()方法一个一个赋值,也可以使用封装的BeanUtils.copy()方法。
配置好 mapstruct 框架也可以帮助再你启动时生成对应的get()与set()方法。
1.pom.xml配置文件
<properties>
<java.version>1.8</java.version>
<mapstruct.version>1.4.1.Final</mapstruct.version>
<maven-compiler-plugin.version>3.8.0</maven-compiler-plugin.version>
</properties>
<dependencies>
<dependency>
<groupId>org.mapstruct</groupId>
<artifactId>mapstruct</artifactId>
<version>${mapstruct.version}</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>${maven-compiler-plugin.version}</version>
<configuration>
<source>${java.version}</source>
<target>${java.version}</target>
<annotationProcessorPaths>
<path>
<groupId>org.mapstruct</groupId>
<artifactId>mapstruct-processor</artifactId>
<version>${mapstruct.version}</version>
</path>
</annotationProcessorPaths>
</configuration>
</plugin>
<plugins>
</build>
2.对应的po类与vo类
class UserPo{
private int id;
private String username;
private Date birthday;
private String headImgUrl;
//get()、set()........
}
class UserVo{
private int id;
private String name;
private String birthday;
private String headImgUrl;
private int age;
//get()、set()........
}
编写对应的接口
@Mapper(unmappedTargetPolicy = ReportingPolicy.IGNORE)
public interface UserConverter {
UserConverter INSTANCE = Mappers.getMapper(UserConverter .class);
@Mappings({
@Mapping(source = "po.id", target = "id"),
@Mapping(source = "po.username", target = "name"),
@Mapping(source = "po.birthday", target = "birthday",qualifiedByName="changeDateToString"),
@Mapping(source = "po.headImgUrl", target = "headImgUrl",qualifiedByName="addHeadUrl"),
@Mapping(source = "age", target = "age")
})
UserVo poToVo(UserPo po,int age,@Context String headUrl)
}
@Named("changeDateToString")
default String changeDateToString(Date birthday){
SimpleDateFormat formatter = new SimpleDateFormat("yyyy年MM月dd日 HH点");
return formatter.format(date);
}
@Named("addHeadUrl")
default String addHeadUrl(String headImgUrl,@Context String headUrl){
return headUrl+headImgUrl;
}
如果vo类与po类属性类型与名称完全相同,且没有其他参数,可以直接这么写
UserVo poToVo(UserPo po)
//List也可以直接复制
Lsit<UserVo> listPoToListVo(List<UserPo> pos)
之后在你启动项目之后会在对应的 target文件夹下生成相应的继承类
如何使用:
UserVo vo = UserConverter.INSTANCE.poToVo(.....);