Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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);
like image 984
Ashwani Tiwari Avatar asked Nov 16 '25 06:11

Ashwani Tiwari


1 Answers

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

like image 138
thanh ngo Avatar answered Nov 17 '25 20:11

thanh ngo