【发布时间】:2020-11-19 15:04:13
【问题描述】:
我正在尝试通过 DTO 创建搜索方法。我的意思是用户可以通过多一个字段搜索产品。您能否为此提出任何更好的方法或帮助降低此方法的复杂性?
public List<ProductDTO> search(SearchProductDTO productDTO) {
Criteria criteria = null;
String insensitive = "i";
if (StringUtils.isNotBlank(productDTO.getName()))
criteria = Criteria.where(NAME.getLabel()).regex(productDTO.getName(), insensitive);
if (StringUtils.isNotBlank(productDTO.getDescription()))
criteria = criteria != null ? criteria.and(DESCRIPTION.getLabel()).regex(productDTO.getDescription(), insensitive) : Criteria.where(DESCRIPTION.getLabel()).regex(productDTO.getDescription(), insensitive);
if (productDTO.getPrice() != 0)
criteria = criteria != null ? criteria.and(PRICE.getLabel()).is(productDTO.getPrice()) : Criteria.where(PRICE.getLabel()).is(productDTO.getPrice());
if (StringUtils.isNotBlank(productDTO.getBrand()))
criteria = criteria != null ? criteria.and(BRAND.getLabel()).regex(productDTO.getBrand(), insensitive) : Criteria.where(BRAND.getLabel()).regex(productDTO.getBrand(), insensitive);
if (productDTO.getProductSize() != null)
criteria = criteria != null ? criteria.and(SIZE.getLabel()).is(productDTO.getProductSize()) : Criteria.where(SIZE.getLabel()).is(productDTO.getProductSize());
if (productDTO.getStockCount() != 0)
criteria = criteria != null ? criteria.and(STOCK_COUNT.getLabel()).is(productDTO.getStockCount()) : Criteria.where(STOCK_COUNT.getLabel()).is(productDTO.getStockCount());
if (StringUtils.isNotBlank(productDTO.getType()))
criteria = criteria != null ? criteria.and(TYPE.getLabel()).regex(productDTO.getType(), insensitive) : Criteria.where(TYPE.getLabel()).regex(productDTO.getType(), insensitive);
if (StringUtils.isNotBlank(productDTO.getColor()))
criteria = criteria != null ? criteria.and(COLOR.getLabel()).regex(productDTO.getColor(), insensitive) : Criteria.where(COLOR.getLabel()).regex(productDTO.getColor(), insensitive);
if (productDTO.getGender() != null)
criteria = criteria != null ? criteria.and(GENDER.getLabel()).is(productDTO.getGender()) : Criteria.where(GENDER.getLabel()).is(productDTO.getGender());
Pageable pageable = PageRequest.of(productDTO.getPage(), productDTO.getSize());
Query query = new Query().with(pageable);
query = criteria != null ? query.addCriteria(criteria).with(pageable) : query;
List<Product> products = mongoTemplate.find(query, Product.class);
return products.stream().map(productMapper::modelToDto).collect(Collectors.toList());
}
【问题讨论】:
-
格式化您的代码并分享一些细节
-
我正在尝试通过 DTO 创建搜索方法。我不能这样做。这就是我写意大利面条代码的原因((
-
您的代码以最佳方式正确编写。只需将圆括号放在下面以便更好地阅读。 if (StringUtils.isNotBlank(productDTO.getDescription())) criteria = (criteria != null ? criteria.and(DESCRIPTION.getLabel()).regex(productDTO.getDescription(), insensitive) : Criteria.where(DESCRIPTION.getLabel ()).regex(productDTO.getDescription(), insensitive));
标签: java spring mongodb spring-boot mongodb-query