@Query named parameters for MongoDb Spring repository

…衆ロ難τιáo~ 提交于 2020-03-23 06:22:07

问题


Is it possible to use named parameters for a @Query method in a mongodb repository, just like we can do with a jpa repository (http://docs.spring.io/spring-data/jpa/docs/1.4.3.RELEASE/reference/html/jpa.repositories.html section 2.3.5)?

As an example, I would like to use the following code:

@Query("{'store' : :store, 'app' : :app }")
List<T> findByStoreAndApp(@Param("store") String store, @Param("app") String app);

instead of:

@Query("{'store' : ?0, 'app' : ?1 }")
List<T> findByStoreAndApp(String store, String app);

回答1:


I'm afraid that the spring boot does provide this function in its source code.

You can create an interface and extends MongoRepository It provides some simple method, and you don't need the implement it. Just like use the JpaRepository.

@NoRepositoryBean
public interface MongoRepository<T, ID extends Serializable> extends PagingAndSortingRepository<T, ID> {
    <S extends T> List<S> save(Iterable<S> var1);

    List<T> findAll();

    List<T> findAll(Sort var1);

    <S extends T> S insert(S var1);

    <S extends T> List<S> insert(Iterable<S> var1);
}

However, if you need to do some special query. You could just @Autowired the MongoTemplate and use its own method. And for redis, springboot even doesn't provide the Repository like MongoRepository. You could just only use the template like StringRedisTemplate for query operation. May be latter, spring boot would add the same function like JpaRepository for NoSql. But now, it doesn't provide this function.




回答2:


It is possible, try:

@Query("{'store' : :#{#store}, 'app' : :#{#app} }")
List<T> findByStoreAndApp(@Param("store") String store, @Param("app") String app);

The support of SpEL expressions in @Query was introduced in Spring Data MongoDB 1.8.



来源:https://stackoverflow.com/questions/38227385/query-named-parameters-for-mongodb-spring-repository

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!