I have a pretty big native query in my Hibernate orm.xml
. I can't easily translate this to HQL or Criterias, but I'd like to have a dynamic where in this query.
It seems TypedQueries isn't a good idea because of SQL injection, Predicates cannot be combined with native queries, so what alternatives are there to create a dynamic where clause?
The dynamic where I have to build are things related to ranges ( between
), lists ( in
queries, etc. I was hoping to create a Predicate and inject it in my query, but no such luck.
This is what my Spring Data JPA interface looks like:
@Query(nativeQuery = true)
fun findNearby(
@Param("latitude") lat: Double,
@Param("longitude") lon: Double,
pageable: Pageable,
@Param("minPopulation") minPop: Int?,
@Param("maxPopulation") maxPop: Int?,
@Param("houseType") type: List<HouseType>?
): Page<AreaSummary>
Ideally, I'd like to combine the population
and the housetype
into a DTO and give that to the query, but I'm happy to consider any working solution.
With a native query there is not much you can do to support dynamic where clauses. The best you could do is try to adapt the native query to support passing null as value for parameters, but I would strongly advise against that if you have a lot of data in that table, as an overly generic query plan will usually result in very bad row estimates which results in a bad physical query plan.
IMO you have two to three options.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.