是转换到DTO这样的好还是不好的做法?



我有一个实体,里面有另一个实体的列表。DTO也是一样,DTO对象带有另一个DTO的列表。

我需要将Entity转换为DTO,其中包含列表。

这是流的样子(有点乱,不知道是否可以使用):

public List<RestaurantDto> getAll() {
List<Restaurant> restaurantList = restaurantRepository.findAll();
return restaurantList.stream()
.map(restaurant -> new RestaurantDto(restaurant.getName(), restaurant.getAddress(),
restaurant.getDishes().stream()
.map(dish -> new DishDto(dish.getId(), dish.getName(), dish.getPrice(), dish.getRestaurant()))
.collect(Collectors.toList())))
.collect(Collectors.toList());
}

这是我的DTO

@Getter
@Setter
@NoArgsConstructor
public class RestaurantDto {
private String name;
private String address;
private List<DishDto> dishes;
private int votes;
public RestaurantDto(String name, String address) {
this.name = name;
this.address = address;
}
public RestaurantDto(String name, String address, List<DishDto> dishes) {
this.name = name;
this.address = address;
this.dishes = dishes;
}
public void addDish(DishDto dishDto) {
dishes.add(dishDto);
}
public List getDeishes() {
return Collections.unmodifiableList(dishes);
}
}

和列表

中的DTO
@Getter
@Setter
@NoArgsConstructor
@ToString
public class DishDto {
private int id;
@NotBlank
private String name;
@Digits(integer = 12, fraction = 2)
private double price;
private String restaurantName;
private String restaurantAddress;
@Digits(integer = 12, fraction = 0)
private int restaurantId;
public DishDto(int id, String name, double price, int restaurantId) {
this.id = id;
this.name = name;
this.price = price;
this.restaurantId = restaurantId;
}
public DishDto(int id, String name, double price, Restaurant restaurant) {
this.id = id;
this.name = name;
this.price = price;
this.restaurantName = restaurant.getName();
this.restaurantAddress = restaurant.getAddress();
this.restaurantId = restaurant.getId();
}

}

我真的很感谢你的帮助!

在我看来,检索整个实体,然后将其转换为dto以拥有更少的字段可以被认为是一种反模式。

如果你想从实体中检索更少的字段,你应该使用投影。

把所有的字段都放到内存中,然后只使用其中的几个,这不是一个好主意。

看一下投影。以下资源可能会有所帮助:

https://vladmihalcea.com/the-best-way-to-map-a-projection-query-to-a-dto-with-jpa-and-hibernate/

https://docs.spring.io/spring-data/jpa/docs/current/reference/html/预测

最新更新