Joins, reporting queries, and subselects If (Web site template) you write

Joins, reporting queries, and subselects If you write JOIN FETCH. without LEFT, you get eager loading with an inner join (also if you use INNER JOIN FETCH ); a prefetch with an inner join, for example, returns Item objects with their bids collection fully initialized, but no Item objects that don t have bids. Such a query is rarely useful for collections but can be used for a many-to-one association that isn t nullable; for example, join fetch item.seller works fine. Dynamic fetching in HQL and JPA QL is straightforward; however, you should remember the following caveats: You never assign an alias to any fetch-joined association or collection for further restriction or projection. So left join fetch i.bids b where b = … is invalid, whereas left join fetch i.bids b join fetch b.bidder is valid. You shouldn t fetch more than one collection in parallel; otherwise you create a Cartesian product. You can fetch as many single-valued associated objects as you like without creating a product. This is basically the same problem we discussed in chapter 13, section 13.2.5, The Cartesian product problem. HQL and JPA QL ignore any fetching strategy you ve defined in mapping metadata. For example, mapping the bids collection in XML with fetch=”join”, has no effect on any HQL or JPA QL statement. A dynamic fetching strategy ignores the global fetching strategy (on the other hand, the global fetch plan isn t ignored every nonlazy association or collection is guaranteed to be loaded, even if several SQL queries are needed). If you eager-fetch a collection, duplicates may be returned. Look at figure 14.3: This is exactly the SQL operation that is executed for a select i from Item i join fetch i.bids HQL or JPA QL query. Each Item is duplicated on the left side of the result table as many times as related Bid data is present. The List returned by the HQL or JPA QL query preserves these duplicates as references. If you prefer to filter out these duplicates you need to either wrap the List in a Set (for example, with Set noDupes = new LinkedHashSet(resultList)) or use the DISTINCT keyword: select distinctifromItemijoinfetchi.bids note that in this case the DISTINCT doesn t operate at the SQL level, but forces Hibernate to filter out duplicates in memory when marshaling the result into objects. Clearly, duplicates can t be avoided in the SQL result.
Please visit our professional web hosting services to find out about cheap and reliable webhost service that will surely answer all your demands.

Leave a Reply