使用 spring data mongodb 存储库添加可选查询参数

2024-05-04

我想使用 spring data mongodb 添加可选查询参数。

控制器代码:

@RestController
private final ActionService actionService;


@RequestMapping(value = "/action/{id}", method = RequestMethod.GET)
public ResponseEntity<List<Action>> getActionList(@PathVariable("id") long id,
            @RequestParam(value = "actionType", required = false) ActionType actionType,
            @RequestParam(value = " ", required = false) String[] params) {

        List<Action> actionList = actionService.getAction(id, actionType, params);
        return new ResponseEntity<>(actionList, HttpStatus.OK);
}

ActionServiceImpl.java

private ActionRepository actionRepository;

public List<Action> getAction(long id, ActionType type, String... var1) {
    return actionRepository.getByActionType(id, type, var1.length > 0 ? var1[0] : "", var1.length > 1 ? var1[1] : "", var1.length > 2 ? var1[2] : "");
}

ActionRepository.java

@Repository
public interface ActionRepository extends MongoRepository<Action, String> {

    @Query(value = "{ 'id' : ?0  , 'actionType' : ?1 ,  'param1' : ?2 , 'param2': ?3 , 'param3' : ?4 } ")
    List<Action> getByActionType(long id, ActionType type, String var1, String var2, String var3);
}

注意:“id”是必填字段,操作类型和参数是可选的。无论是否传递操作类型/参数,我都想根据“id”获取数据。目前,我在“ActionServiceImpl”中遇到空指针异常,因为我没有传递参数和操作类型。 “动作类型”是枚举。

有人可以帮助我更改 ActionRepository @Query 标签,这样我就可以根据 id 获取数据,而无需传递 actionType 或参数。例如如果我传递操作类型,那么 mongo 查询应该根据“id $or actionType”给出结果。


您无法使用以下方法实现此目的@Query。其他可能的替代方案是

  1. 在 Repository 类中创建两个方法。一种只接受 id,另一种接受 id 和其他参数。而在你的服务类中,你可以根据手头的数据决定调用哪一个。(不可扩展)

  2. 使用 QueryDsl。通过此功能,您可以根据动态数据创建搜索条件。一些有用的链接
    https://docs.spring.io/spring-data/mongodb/docs/current/reference/html/#core.extensions.querydsl https://docs.spring.io/spring-data/mongodb/docs/current/reference/html/#core.extensions.querydsl
    http://www.baeldung.com/queries-in-spring-data-mongodb http://www.baeldung.com/queries-in-spring-data-mongodb

  3. 您可以使用Example. Here https://docs.spring.io/spring-data/mongodb/docs/current/reference/html/#query-by-example是文档的链接。(这有一些限制)

根据我个人的经验,使用 QueryDsl 是解决这些情况的最佳方法,并且可以轻松扩展它以适应需求的进一步变化。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

使用 spring data mongodb 存储库添加可选查询参数 的相关文章

随机推荐