I am using Spring JPA Specifications to create criteria query. My code looks like this:
public CollectionWrapper<OrderTableItemDto> getOrders(Integer page,
Integer size,
String search,
OrderShow show) {
Pageable pageable = PageRequest.of(page, size, Sort.by(OrderEntity_.ID).descending());
try {
Specification<OrderEntity> specifications = buildOrderSpecification(show, search);
Page<OrderEntity> orders = orderDao.findAll(specifications, pageable);
List<OrderTableItemDto> result = orders.getContent().stream().map(order -> {
OrderTableItemDto orderTableItemDto = new OrderTableItemDto();
orderTableItemDto.setCreatedDate(order.getCreatedDate());
orderTableItemDto.setCustomerId(order.getCustomer().getId());
orderTableItemDto.setId(order.getId());
orderTableItemDto.setStatus(order.getStatus());
orderTableItemDto.setTotalCost(order.getTotalCost());
orderTableItemDto.setOrderType(order.getOrderType());
orderTableItemDto.setOrderTypeLabel(order.getOrderType().getLabel());
if(order.getOrderInShippingMethod() != null) {
orderTableItemDto.setShipped(OrderShippingStatus.DELIVERED.equals(order.getOrderInShippingMethod().getStatus()));
} else {
orderTableItemDto.setShipped(false);
}
StringBuilder sb = new StringBuilder();
sb.append("#")
.append(order.getId())
.append(" ");
if(order.getOrderType().equals(OrderType.WEB_STORE)) {
sb
.append(order.getBilling().getFirstName())
.append(" ")
.append(order.getBilling().getLastName());
} else {
sb.append(order.getCustomer().getFullName());
}
orderTableItemDto.setTitle(sb.toString());
return orderTableItemDto;
}).collect(Collectors.toList());
return new CollectionWrapper<>(result, orders.getTotalElements());
I was told it is bad approach and that i should use projections (DTOs) to read from database, because it is expensive to create entities and to map them afterward. The problem is that I do not know how can I combine specifications with DTOs. What would be the optimal way in order to manage complex and dynamic queries (filters from user inputs etc.) with complex DTOs which contains nested DTOs and lots of properties?