HQL: Fetch Join Collections from Eager Table

前端 未结 2 1890
借酒劲吻你
借酒劲吻你 2021-02-16 00:12

I have four tables:

RootNode // Will return multiple root nodes 
SubNode // Will return one sub node per root node
SubNodeChildren1 // Will return multiple for e         


        
2条回答
  •  既然无缘
    2021-02-16 00:56

    Here goes Hibernate reference

    The only reason we might need an alias is if we are recursively join fetching a further collection

    Which implies your query should be re-written as

    select distinct 
        rn
    from
        RootNode rn
    left join fetch 
        rn.subNode sn
    left join fetch 
        sn.subNodeChildren
    

    You can either

    disable default subNode fetch=FetchType.EAGER and just retrieve what you really want by using HQL query - It (HQL query) effectively overrides the outer join and lazy declarations of the mapping file for associations and collections (Hibernate reference documentation). This approach is supported by POJO in Action book.

    or enable the collection of SubNodeChildren as fetch=FetchType.EAGER

    The following has been extracted from the Hibernate FAQ (The link has been disabled (As far as i know) but i have saved before disappearing)

    In an MVC application, how can we ensure that all proxies and lazy collections will be initialized when the view tries to access them ?

    One possible approach is to leave the session open (and transaction uncommitted) when forwarding to the view. The session/transaction would be closed/committed after the view is rendered in, for example, a servlet filter (another example would by to use the ModelLifetime.discard() callback in Maverick). One difficulty with this approach is making sure the session/transaction is closed/rolled back if an exception occurs rendering the view.

    ...

    Another approach is to simply force initialization of all needed objects using Hibernate.initialize(). This is often more straightforward than it sounds.

提交回复
热议问题