java 如何在mongodb spring Boot 中进行排序和搜索

jhiyze9q  于 2022-12-17  发布在  Java
关注(0)|答案(1)|浏览(183)

我无法使用Mongodb对搜索结果进行排序,我添加了一个使用findAllByorderByDateDesc()的方法查询
我试着使用“findAllByOrderByDateDesc(),如果我不做搜索查询,它会工作,但一旦我添加了@Query注解,它就停止按日期排序。
储存库

@Repository
public interface WarrantiesRepository extends MongoRepository<WarrantyModel, String> {
    public Page<WarrantyModel> findAllByOrderByDateDesc(PageRequest pageRequest);

    @Query("{$text: {$search: ?0}}")
    public Page<WarrantyModel> findAllByOrderByDateDesc(String search, PageRequest pageRequest);
    public WarrantyModel getWarrantyById(String id);
    public WarrantyModel getWarrantyByCar(String car);
    public WarrantyModel getWarrantyByPart(String part);
    public WarrantyModel getWarrantyBypartNumber(String partNumber);
}

主计长

@PostMapping("/warranties/search")
    public ModelAndView getLiveWarranties(@RequestBody String search, Model model) {
        input = search.substring(1, search.length()-1);
        if(search.length() == 2) {
            warranties = warrantiesRepository.findAllByOrderByDateDesc(PageRequest.of(currentPage, pageSize));
        } else {
            warranties = warrantiesRepository.findAllByOrderByDateDesc(search, PageRequest.of(currentPage, pageSize));
        }
        ModelAndView mv = new ModelAndView("warranties::search");
        mv.addObject("warranties", warranties);
        
        return mv;
    }

型号

@Component
@Document("Warranty")
public class WarrantyModel {
    
    @Id
    public String id;
    
    @TextIndexed
    public String car;
    @TextIndexed
    public String part;
    public String store;
    @TextIndexed
    public String partNumber;
    public String warranty;
    public LocalDate date;
    
Constructors/getter/setters

Search Queries

vmdwslir

vmdwslir1#

这是预期的行为。默认情况下,"... Repository“的所有方法都是”派生查询方法“,Spring尝试根据方法名称Map实现(它将为您生成查询)。
一旦您使用@Query注解来注解一个方法,Spring希望您指定自己的查询,并且不管方法的名称如何,它都不会自己进行任何派生。
查看此文章以获取更详细的说明-Spring Data MongoDB - Guide to the @Query Annotation

相关问题