Search code examples
hibernatejpahibernate-criteria

Convert an SQL Query that includes join fetch to a Criteria Hibernate query


I am trying to convert the following query:

Query query = entityManager.createQuery("from TestEntity te " +
                    "join fetch te.someEntity se " +  
                    "left join fetch te.someEntity2 se2 "
                    "left join fetch se2.someEntity3 " +
                    "where se.predicateHere =:prediacte");

to a Criteria Hibernate Query, but definitely missing something because I am getting the following error:

query specified join fetching, but the owner of the fetched association was not present in the select list

When I try this:

Root<TestEntity> testEntityRoot = criteria.from(TestEntity.class);
testEntityRoot.fetch(TestEntity_.someEntity, JoinType.INNER);
testEntityRoot.fetch(TestEntity_.someEntity2, JoinType.LEFT).fetch(SomeEntity2.someEntity3, JoinType.LEFT);

Sorry about the table/column naming, but it's sensitive data.


Solution

  • I ended up solving the issue using this same query:

    Root<TestEntity> testEntityRoot = criteria.from(TestEntity.class);
    testEntityRoot.fetch(TestEntity_.someEntity, JoinType.INNER);
    testEntityRoot.fetch(TestEntity_.someEntity2, JoinType.LEFT).fetch(SomeEntity2.someEntity3, JoinType.LEFT);
    

    Except that I was fetching entities in the wrong order.

    First we need to fetch the root entity, and then chain any fetches to get to the the one we want.