Home > Software design >  Dynamic query with @Query in Spring Data JPA?
Dynamic query with @Query in Spring Data JPA?

Time:12-06

I am using Specifications in my Spring Boot app and can filter result by different filter options. However, I need to use special filter with @Query in my repository method and as far as I see, I cannot build a dynamic WHERE clause in this query.

There are also QueryDSL and CriteriaAPI options, but I cannot find an example for using them in @Query.

So, is it possible to dynamically build WHERE clause or create filter for the query in @Query? Here is my method:

// there are more filters that omitted for brevity 

@Query("SELECT r FROM Recipe r WHERE r.title LIKE %:text%")
Page<Recipe> findByFields(@Param("text") String text);

I tried to use my specification in this method, but it is not possible to use them with @Query :((

CodePudding user response:

You can try like this:

@Query("SELECT r FROM Recipe r WHERE r.title LIKE %?1%")
Page<Recipe> findByFields(String text);

CodePudding user response:

@Query can only do static queries.

If you want something more dynamic you have to use another feature, for example Specifications or even fall back to custom method implementations.

  • Related