简体   繁体   English

Spring 数据 JPA 本机查询的动态 where 子句

[英]Dynamic where clause for Spring Data JPA native query

I have a pretty big native query in my Hibernate orm.xml .我的 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.我不能轻易地将它翻译成 HQL 或 Criterias,但我想在这个查询中有一个动态的 where。

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?似乎 TypedQueries 不是一个好主意,因为 SQL 注入,谓词不能与本机查询结合,那么有什么替代方法来创建动态 where 子句?

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.我必须构建的动态是与范围( between )、列表( in查询中等)相关的东西。我希望创建一个谓词并将其注入我的查询中,但没有这样的运气。

This is what my Spring Data JPA interface looks like:这是我的 Spring 数据 JPA 界面的样子:

@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.理想情况下,我想将populationhousetype成一个 DTO 并将其提供给查询,但我很乐意考虑任何可行的解决方案。

With a native query there is not much you can do to support dynamic where clauses.使用本机查询,您无能为力来支持动态 where 子句。 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.您可以做的最好的事情是尝试调整本机查询以支持将 null 作为参数值传递,但如果您在该表中有大量数据,我强烈建议您不要这样做,因为过于通用的查询计划通常会导致非常错误的行估计会导致错误的物理查询计划。

IMO you have two to three options. IMO 你有两到三个选择。

  1. Create SQL queries for all possible filtering combinations and dispatch to respective repository methods为所有可能的过滤组合创建 SQL 查询并分派到相应的存储库方法
  2. Migrate to the JPA Criteria API迁移到 JPA 标准 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.如果 2. 不起作用,因为您需要高级 SQL 功能,请查看Blaze-Persistence ,因为它可能仅通过在核心业务逻辑之上工作的实体视图映射公开您需要的 SQL 功能,特别是因为属性过滤是动态的. Contact me if you need more help for this, as I am the maintainer of that library如果您需要更多帮助,请联系我,因为我是该库的维护者

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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