简体   繁体   中英

Hibernate generates invalid query

I am using Spring Data @Query annotation to select some values from the database. 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

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

which does not return anything.

I am using Microsoft SQL Server 2017 (RTM). Hibernate configuration is like this:

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 '=')?

既然 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.

With nativeQuery = true you must supply a valid SQL query that conforms to the underlying database dialect.

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. 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

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