简体   繁体   English

Hibernate 生成无效查询

[英]Hibernate generates invalid query

I am using Spring Data @Query annotation to select some values from the database.我正在使用 Spring Data @Query 注释从数据库中选择一些值。 The query look like this (simplified)查询看起来像这样(简化)

@Query("from #{#entityName} where :myParam is null or someAttribute not in :myParam")

This should create equivalent SQL that should return all records from the table if the myParam value is null, however hibernate create the where clause like this如果 myParam 值为空,这应该创建等效的 SQL,该 SQL 应该从表中返回所有记录,但是 hibernate 会像这样创建 where 子句

... where :myParam = null or ...

which does not return anything.它不返回任何东西。

I am using Microsoft SQL Server 2017 (RTM).我正在使用 Microsoft SQL Server 2017 (RTM)。 Hibernate configuration is like this: Hibernate的配置是这样的:

spring.datasource.driver-class-name: com.microsoft.sqlserver.jdbc.SQLServerDriver
spring.jpa.database-platform: org.hibernate.dialect.SQLServer2012Dialect

How can I ensure that the Hibernate generates correct query (ie using 'is' instead of '=')?如何确保 Hibernate 生成正确的查询(即使用“is”而不是“=”)?

既然 JPA 支持coalesce为什么不@Query("from #{#entityName} where coalesce(someAttribute, :myParam) = :myParam)

If you don't add nativeQuery = true to @Query annotation, the query must be a valid JPQL query and it's the JPA's implementor's responsability (hibernate) to translate JPQL queries to underlying database SQL dialect.如果您不将nativeQuery = true添加到@Query注释,则查询必须是有效的 JPQL 查询,并且 JPA 的实现者有责任(休眠)将 JPQL 查询转换为底层数据库 SQL 方言。

With nativeQuery = true you must supply a valid SQL query that conforms to the underlying database dialect.使用nativeQuery = true您必须提供符合基础数据库方言的有效 SQL 查询。

I'd be really surprised if this is really what is happening.如果这真的发生了,我会非常惊讶。 My guess, your @Query annotation is not picked up and Spring Data uses the method name convention or you didn't share the correct query.我的猜测是,您的@Query注释没有被选中并且 Spring Data 使用了方法名称约定,或者您没有共享正确的查询。 Either way, if this really is a hibernate bug(maybe you are using a very old hibernate version), you should create an issue with a test case that reproduces the issue: http://hibernate.atlassian.net无论哪种方式,如果这确实是一个休眠错误(也许您使用的是非常旧的休眠版本),您应该使用重现该问题的测试用例创建一个问题: http : //hibernate.atlassian.net

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

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