在将 DTO 转换为实体 bean 以及从实体 bean 转换为 DTO 时,您可以使用 ModelMapper。
将 ModelMapper 添加到您的项目中
<dependency>
<groupId>org.modelmapper</groupId>
<artifactId>modelmapper</artifactId>
<version>2.3.5</version>
</dependency>
在 Spring 配置中定义 ModelMapper bean
@Bean
public ModelMapper modelMapper() {
return new ModelMapper();
}
根据您给出的给定 ER 图假设以下模型
public class UserDto {
Integer userId;
String role;
String username;
String password;
boolean enabled;
...default and parameterized constructor
...getter and setter methods
}
public class ProductDto {
Integer productId;
String imageUrl;
String category;
int productPrice;
int productQuantity;
String productName;
String productDesc;
...default and parameterized constructor
...getter and setter methods
}
public class RatingDto {
@Id
Integer id;
int rating;
String review;
String ratingscol;
ProductDto productDto;
UserDto userDto;
...default and parameterized constructor
...getter and setter methods
}
您可以通过以下方法使用产品 ID 和用户详细信息检索产品的评级
@Repository
public interface RatingRepository extends JpaRepository<Rating, Integer>{
List<Rating> findByProduct_ProductId(Integer productId);
}
然后将评级对象映射到 DTO
RatingDto ratingDto = modelMapper.map(rating, RatingDto.class);
现在您可以按以下方式检索用户名
ratingsDto.getUserDto().getUserName()
与通过 userId 检索评级和访问产品详细信息的方式相同