本文介绍了Spring Data JPA Repositories:是否可以给params一个默认的Value / default all?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

因此,简而言之:是否可以将参数设置为default:All或更一般地将其设置为Spring Data JPA中的默认特定值(可能是@ Query-Annotated)Repository-Methods?

So, in short terms: Is it possible to set a parameter to "default: All" or more generally to a default specific value in Spring Data JPA (possibly @Query-Annotated) Repository-Methods?

我(Rest)控制器可以设置默认值价值,我只是好奇,如果它也可以在存储库级别进行。我认为可能是一个很好的功能,因为让我得到一些过滤的结果集,其中过滤器可能没有在前端通过休息调用设置过滤器是一个非常常见的用例。

I'm aware that it's possible in (Rest)controllers to set a default Value, i'm just curious if it's possible to do it at Repository-Level, too. Might be a nice feature I think, for "get me some filtered resultSet where filters might be not set in frontend by a rest-call" is a very common use-case.

示例 - 查询:

@Query("select new com.my.dto(e.name, e.age, e.address)" +
        " from Entity e" +
        "where e.name like ?1 " +
        "and e.age like ?2  " +
        "and e.street like ?3")
List<Item> findItemsFiltered(String name, String age, String street);

所以当我们说没有设置street时,存储库应该使用%来返回所有结果其他标准是匹配但街道不相关。

So when let's say street is not set, the Repository should use "%" to return all Results where the other criteria is matching but the street is not relevant.

推荐答案

如何在中进行操作查询本身?
类似于:

How about doing it in the @Query itself?Something like:

@Query("select new com.my.dto(e.name, e.age, e.address)" +
    " from Entity e" +
    "where e.name like ?1 " +
    "and e.age like ?2  " +
    "and e.street like (CASE WHEN ?3 IS NULL THEN '%' ELSE ?3 END)")
List<Item> findItemsFiltered(String name, String age, String street);

另一种方法是使用自定义参数注释,如 @Default 但是我需要自定义存储库实现本身。

Another way would be to have a custom parameter annotation like @Default but that would require customizing the repository implementation itself I believe.

另一种选择是规范正如M. Deinum所说。

Another alternative is the Specification as M. Deinum mentioned.

这篇关于Spring Data JPA Repositories:是否可以给params一个默认的Value / default all?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-29 17:21