CTE usage with Spring Data JPA 3.2 + Hibernate 6.4 Does not work

107 Views Asked by At

I am using current latest version of Spring Data Jpa. As per the release notes and PRs Spring Data JPA should support CTE / Recursive CTE . Following are the links for confirmation :

  1. https://github.com/spring-projects/spring-data-jpa/issues/2981
  2. https://github.com/spring-projects/spring-data-jpa/releases/tag/3.2.0
  3. https://in.relation.to/2023/02/20/hibernate-orm-62-ctes/

But I have tried HQL that Contains CTE in NamedQuery / Query / entityManager.createQuery in Spring Boot Application but none works.

Samples:

WITH samCTE AS (
            select f.id as id, f.parentFolderId as parentFolderId, f.programBookId as programBookId, f.name as name, CAST('' as String) as pathInQueriedParent
            from Hierarchy f
            where f.id = :folderId
            UNION ALL
            select child.id as id, child.parentFolderId as parentFolderId, child.programBookId as programBookId, child.name as name, CAST(CONCAT(parent.pathInQueriedParent, '/', child.name) as String) as pathInQueriedParent
            from Hierarchy child
            join samCTE parent ON parent.id = child.parentFolderId
        )
        select fp.id, fp.parentFolderId, fp.programBookId, fp.name, pathInQueriedParent
        from samCTE fp

I have @Entity annotation over Hierarchy entity. Issue is it does not recognises "samCTE" and expects it to be entity as well.

    Caused by: org.hibernate.query.sqm.EntityTypeException: Could not resolve entity name 'samCTE'

I strongly believe that it is issue with validation only as after using the below work around it does not raise any error at time of converting to native sql at time of running the Query.

For a workaround I am currently using Blaze-persistence to Define Entity for samCTE with help of @CTE tag. But I don't think its mentioned in hibernate documentation that we need to define entity for CTE explicitly.

Second Problem:

from dbo.Hierarchy a1_0 left join ( select * samCTE ) f4_0

When I check the native query in sql logs , then I see the join is using join on subselect rather than direct join. This can still produce results but I am not sure if it can change query plans and can be more expensive.

0

There are 0 best solutions below