在Java中,可以使用以下方法来实现两个实体类之间的相互转换:
public class EntityA {
private int id;
private String name;
// getters and setters
}
public class EntityB {
private int id;
private String name;
// getters and setters
}
// 将EntityA转换为EntityB
public EntityB convertToEntityB(EntityA entityA) {
EntityB entityB = new EntityB();
entityB.setId(entityA.getId());
entityB.setName(entityA.getName());
return entityB;
}
// 将EntityB转换为EntityA
public EntityA convertToEntityA(EntityB entityB) {
EntityA entityA = new EntityA();
entityA.setId(entityB.getId());
entityA.setName(entityB.getName());
return entityA;
}
// 添加ModelMapper依赖库
<dependency>
<groupId>org.modelmapper</groupId>
<artifactId>modelmapper</artifactId>
<version>2.3.8</version>
</dependency>
// 使用ModelMapper进行转换
import org.modelmapper.ModelMapper;
public class EntityA {
private int id;
private String name;
// getters and setters
}
public class EntityB {
private int id;
private String name;
// getters and setters
}
// 将EntityA转换为EntityB
public EntityB convertToEntityB(EntityA entityA) {
ModelMapper modelMapper = new ModelMapper();
EntityB entityB = modelMapper.map(entityA, EntityB.class);
return entityB;
}
// 将EntityB转换为EntityA
public EntityA convertToEntityA(EntityB entityB) {
ModelMapper modelMapper = new ModelMapper();
EntityA entityA = modelMapper.map(entityB, EntityA.class);
return entityA;
}
上述两种方法可以根据具体的需求选择其中一种来实现实体类之间的相互转换。