简体   繁体   中英

Dynamic where clause for Spring Data JPA native query

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.

  1. Create SQL queries for all possible filtering combinations and dispatch to respective repository methods
  2. Migrate to the JPA Criteria API
  3. If 2. doesn't work because you need advanced SQL features, look into Blaze-Persistence as might expose just the SQL features you need through Entity-View mappings which work on top of the core business logic, in particular because attribute filtering is dynamic. Contact me if you need more help for this, as I am the maintainer of that library

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM