首先贴上源码
public interface DTOConvert<T, S> {
/**
* 转化
* @param s
* @return
*/
T convert(S s);
}
我们将所用的数据分成三种类型 Entity实体类,Params传参,DTO出参
@Data
@Accessors(chain = true)
public class StudentParams{
private String unid;
private String name;
private String phone;
public StudentEntity converToEntity() {
StudentParamsConvert convert = StudentParamsConvert.newConvert();
converToEntityentity = convert.convert(this);
return entity;
}
@NoArgsConstructor(staticName = "newConvert")//构造无参函数
private static class StudentParamsConvert implements DTOConvert<StudentEntity, StudentParams>{
@Override
public StudentEntity convert(StudentParams params) {
StudentEntityentity = StudentEntity.newEntity();
BeanUtils.copyProperties(params, entity);//parmas为来源,entity为目标
//将source数据导入转换到entity中
return entity;
}
}
本文介绍了一种在Java中实现对象转换的方法,通过定义接口DTOConvert和具体实现类StudentParamsConvert,实现了从StudentParams到StudentEntity的对象转换。使用了Lombok注解简化代码,并通过BeanUtils工具类完成属性复制。

180

被折叠的 条评论
为什么被折叠?



