Is there a way to use constants inside Spring Data @Query annotation value?

Roman picture Roman · Aug 23, 2013 · Viewed 33.9k times · Source

I don't want to hardcode constant values, I would rather specify them through a reference variable.

For example, rather then writing the next query:

@Query(value = "SELECT u FROM UserModel u WHERE u.status = 1")

..I would like to extract the hardcoded value '1' and write something like:

@Query(value = "SELECT u FROM UserModel u WHERE u.status = UserModel.STATUS_ACTIVE")  //doesn't compile

Is there a way to specify constants like in the second example inside spring-data queries?

Answer

Cleankod picture Cleankod · Mar 4, 2014

You have to use fully qualified class name like this:

@Query("SELECT u FROM UserModel u WHERE u.status = com.example.package.UserModel.STATUS_ACTIVE")

The bad thing about it though is that an IDE would not recognise this as an usage of the class UserModel. The only advantage is that you can keep the value in one place, which is sufficient most of the time. This has been resolved in IntelliJ IDEA 2017.1. I don't know about other IDEs.