How to convert two Java entity classes to each other?
In Java, the following methods can be used to achieve mutual conversion between two entity classes:
- Manually convert: Create a new entity class object, and then set the property values of the new entity class object using the property values of the source entity class object.
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;
}
- Utilizing a third-party library, such as ModelMapper, can automatically convert property values between two entity classes.
// 添加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;
}
One of the two methods mentioned above can be chosen based on specific needs to achieve mutual conversion between entity classes.