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?
The @Query annotation supports both JPQL and SQL queries.
Understanding the @Query Annotation The @Query annotation can only be used to annotate repository interface methods. The call of the annotated methods will trigger the execution of the statement found in it, and their usage is pretty straightforward. The @Query annotation supports both native SQL and JPQL.
Spring Data JPA allows you to add a special Sort parameter to your query method. The Sort class is just a specification that provides sorting options for database queries. By using dynamic sorting, you can choose the sorting column and direction at runtime to sort the query results.
The @Query annotation can be used to create queries by using the JPA query language and to bind these queries directly to the methods of your repository interface.
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.
I would recommend creating an Enum
and a field of that enum on the entity.
public enum UserModelStatus{
ACTIVE, INACTIVE
}
public UserModel{
/* Other fields ommitted */
@Enumerated(EnumType.STRING)
private UserModelStatus status;
/* Get/Set Method */
}
Then create your repository method:
@Repository
public interface UserModelRepository extends JpaRepository<UserModel, Long>{
public List<UserModel> findByStatus(UserModelStatus status);
}
Using Spring Data you won't even need to write JPQL just call the method like:
@Autowired
UserModelRepository userModelRepository;
public void someMethod(){
List<UserModel> userModels = userModelRepository.findByStatus(UserModelStatus.ACTIVE);
}
Use as follows:
In the repository interface, define a constant as follows:
public static final String USER_QUERY = "SELECT u FROM UserModel u WHERE u.status = " + UserModel.STATUS_ACTIVE;
Now you can use
@Query(value=USER_QUERY)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With