将DTO转换为实体,反之亦然
问题描述:
我在我的网络应用程序中使用 Spring MVC
架构与 JPA
。
I am using Spring MVC
architecture with JPA
in my web application.
手动将DTO转换为实体的位置(反之亦然)(不使用任何框架)?
Where to convert DTO to entity and vice-versa manually(without using any framework)?
答
我想你问的是在哪里写整个实体 - > DTO转换逻辑。
I think you are asking about where to write whole entity-->DTO conversion logic.
喜欢你的实体
class StudentEntity {
int age ;
String name;
//getter
//setter
public StudentDTO _toConvertStudentDTO(){
StudentDTO dto = new StudentDTO();
//set dto values here from StudentEntity
return dto;
}
}
你的DTO应该像
class StudentDTO {
int age ;
String name;
//getter
//setter
public StudentEntity _toConvertStudentEntity(){
StudentEntity entity = new StudentEntity();
//set entity values here from StudentDTO
return entity ;
}
}
你的控制器应该像
@Controller
class MyController {
public String my(){
//Call the conversion method here like
StudentEntity entity = myDao.getStudent(1);
StudentDTO dto = entity._toConvertStudentDTO();
//As vice versa
}
}