可选的 hql 查询参数

Optional hql query parameters

我有一个休息存储库:

@Query(
            "SELECT ord FROM Order as ord where " +
                    " (:#{#customer} is null or :#{#customer}='' or  ord.customer = :#{#customer}) and " +
                    " (:#{#supplier} is null or :#{#supplier}='' or ord.supplier = :#{#supplier} ) and " +
                    " (:#{#startDate} is null or :#{#startDate}='' or ord.date >= :#{#startDate} ) and " +
                    " (:#{#endDate} is null or :#{#endDate}='' or ord.date >= :#{#endDate} )"
    )
    Page<Order> query(
            @Param("customer") Organization customer,
            @Param("supplier") Organization supplier,
            @DateTimeFormat(pattern = "dd-MM-yyyyy") @Param("startDate") Date startDate,
            @DateTimeFormat(pattern = "dd-MM-yyyyy") @Param("endDate") Date endDate,
            Pageable pageable
    );

当我调用不带任何参数的查询时,它工作正常并且 returns 每个订单。如果我提供任何一个参数而不提供其余参数,我会得到 org.hibernate.QueryException: Not all named parameters have been set。有解决办法吗?

您将 SpEL 混合用于实体名称和绑定参数。对于绑定使用 ':parameterName' 而不是 ':#{#parameterName} '

@Query(
            "SELECT ord FROM Order as ord where " +
                    " (:customer is null or :customer='' or  ord.customer = :customer) and " +
                    " (:upplier is null or supplier='' or ord.supplier = :supplier) and " +
                    " (:startDate is null or :startDate='' or ord.date >= :startDate) and " +
                    " (:endDate is null or :endDate='' or ord.date >= :endDate )"
    )
    Page<Order> query(
            @Param("customer") Organization customer,
            @Param("supplier") Organization supplier,
            @DateTimeFormat(pattern = "dd-MM-yyyyy") @Param("startDate") Date startDate,
            @DateTimeFormat(pattern = "dd-MM-yyyyy") @Param("endDate") Date endDate,
            Pageable pageable
    );