6

I have a name query like the one below - but keep getting an error from Hibernate that it will not allow my 'with'-clause since I'm doing join fetch.

I need to do join fetch - because it there is a related item then I wan't it to be present on the object.

    @NamedQuery(name = "Item.findItem", 
        query = "SELECT DISTINCT(c) FROM Item c " +                 
                "JOIN FETCH c.storeRelations as childStoreRelation " +                                                              
                "LEFT JOIN FETCH c.relatedItems as relatedRelations WITH relatedRelations.store.id = childStoreRelation.store.id " +
                "WHERE c.id = :itemId " +                                                                   
                "AND childStoreRelation.store.id = :storeId " +
                "AND childStoreRelation.deleted <> 'Y' " +
                "ORDER BY c.partnumber "),

Suggestion would be to move the 'with' part to my where clause - but this will cause invalid results.

Consider item A which might have to items related to it - but for some stores the relations are not valid.

If put in where clause then the store without relations will not shown the main item, since SQL will be build by Hibernate so it requires that if any relations exist, then they must be valid for the store - otherwise nothing is fetched :-(

So the classic fix found many places (store.id is null OR store.id = :storeId) will not work.

Does someone have another work around?

I'm running Hibernate 4.3.11

Thanks in advance

2 Answers2

0

You cannot use LEFT JOIN FETCH with clause. Please remove WITH clause and move them to WHERE clause.

It should like this:

@NamedQuery(name = "Item.findItem", 
    query = "SELECT DISTINCT(c) FROM Item c " +                 
            "JOIN FETCH c.storeRelations as childStoreRelation " +                                                              
            "LEFT JOIN FETCH c.relatedItems as relatedRelations " +
            "WHERE c.id = :itemId " +     
            "AND relatedRelations.store.id = childStoreRelation.store.id" +                                 
            "AND childStoreRelation.store.id = :storeId " +
            "AND childStoreRelation.deleted <> 'Y' " +
            "ORDER BY c.partnumber "),
İsmail Y.
  • 3,579
  • 5
  • 21
  • 29
Vu Phan
  • 1
  • 1
-5

You need the ON keyword rather than the WITH keyword.

O. Jones
  • 103,626
  • 17
  • 118
  • 172