Ashwani Tiwari
Ashwani Tiwari

Reputation: 1567

Pass the dynamically created query (according to condition) in @Query annotation

I am using the @Query annotation to execute the query in spring repository. But I want to change the some part or make a new query according to the condition and pass in the @Query("pass here the query according to condition")

This is my query

  @Query("SELECT ds.symptom  FROM DoctorSymptomsModel ds where ds.doctorId = :doctorId and ds.isMostUsed = :isMostUsed)

If some condition satisfy then concat the "ORDER BY createdDate" part in query.

Or

Can I make the variable and set the query in that variable and set like that

  String query = SELECT ds.symptom  FROM DoctorSymptomsModel ds where
  ds.doctorId = :doctorId and ds.isMostUsed = :isMostUsed

  if(result){

  query = SELECT ds.symptom  FROM DoctorSymptomsModel ds where ds.doctorId =
  :doctorId and ds.isMostUsed = :isMostUsed ORDER BY createdDate


}

    //pass the query variable here
    @Query(query)
    List<String> findDoctorSymptomsModelList(@Param("doctorId") long doctorId,
    @Param("isMostUsed") boolean isMostUsed);

Upvotes: 3

Views: 2649

Answers (1)

thanh ngo
thanh ngo

Reputation: 844

To make a dynamic query, you should think about CriteriaQuery. Take a look at this link for brief introduction.

Upvotes: 2

Related Questions