馃巿Using param object in Spring 馃崈 Data JPA query

Jan Cizmar - Jan 12 '22 - - Dev Community

Spring Boot JPA repositories are very simple and useful approach how to get data we need for our business logic. Instead of implementing methods, which would execute queries, we can just annotate repository methods with @Query annotation. Spring automatically implements these methods using proxies and we don't have to care, what happens under the hood.

We can simply pass variables by defining them as parameters of the annotated methods and using them in the query with : prefix.



  @Query("from Project p where p.user = :userAccount")
  fun getAllUserProjects(userAccount: UserAccount): List<Project>


Enter fullscreen mode Exit fullscreen mode

This is great, but what we need to pass more params to the query, like more complex filters? Can we do that using object encapsulating these parameters? Yes we can! Spring supports also using SpEL in the JPA Queries!



  @Query("""from UserAccount 
    where u.firstname = :#{#customer.firstname}""")
  fun findCoolUsers(
    @Param("customer")
    customer: UserAccount
  ): List<UserAccount>


Enter fullscreen mode Exit fullscreen mode

This is very useful, when we need to pass many parameters to our query and we don't want to define many function parameters.


Tolgee is an open-source solution for software localization. It saves developer's time. Go to Tolgee.io and have fun!

Image description

. . . . . . . . . . . . . . . . . . . . . . . . .