spring data compose @query query dynamically

2019-01-15 22:43发布

问题:

I have situation in which I have to compose a JPQL query in some method, then pass this query to spring data query method to be used as the query in @Query annotation

@Query(value = ":DyanamicQuery")
List<PrizeInsuranceConfiguration> filterConfigurPrizeInsurance(String DyanamicQuery);

or at least the conditions part

@Query(value = "SELECT c FROM PrizeInsuranceConfiguration c WHERE  :DyanamicConditions")
List<PrizeInsuranceConfiguration> filterConfigurPrizeInsurance(String DyanamicConditions);

回答1:

Do, you can do that. There are two reasons why not:

  1. sql injection (spring data work with prepared statements);
  2. (result of first reasone) spring data create query tree and bind all params

But if you need dynamic query you can use Specifications, Query by Example or Querydsl.