4

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);

2 Answers 2

21

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://docs.spring.io/spring-data/mongodb/docs/current/reference/html/#mongo.aggregation.projection.expressions

Sign up to request clarification or add additional context in comments.

Comments

0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.