jpa fetch join query

10,256

You cannot use an alias on a join fetch in JPQL, this is disallowed by the spec.

EclipseLink does allow nested join fetch through the query hint,

"eclipselink.join-fetch"="t.fieldConfig.fieldSet"
Share:
10,256
Frédéric Gobert
Author by

Frédéric Gobert

Updated on June 04, 2022

Comments

  • Frédéric Gobert
    Frédéric Gobert almost 2 years

    This is how my domain looks:

    public class Template implements Serializable {
        private static final long serialVersionUID = 1L;    
        @OneToOne(cascade=CascadeType.ALL)
        private FieldConfig fieldConfig;
    }
    
    public class FieldConfig implements Serializable {
        private static final long serialVersionUID = 1L;
    
        @OneToMany(cascade= CascadeType.PERSIST)
        @JoinColumn(name = "fieldConfigId")
        private Set<Field> fieldSet;
    }
    

    I want to achieve if I load a template from the db that automatically the fieldConfig is loaded and the fieldSet of that fieldconfig.

    my current JPQL:

    TypedQuery<Template> query = em.createQuery("SELECT t from Template t LEFT JOIN FETCH t.fieldConfig"
                    + " fconfig LEFT JOIN FETCH fconfig.fieldSet where t.id = :id", Template.class);
    

    my exception:

    Internal Exception: NoViableAltException(80@[()* loopback of 477:9: (node= join )*])
    Exception Description: Syntax error parsing the query [SELECT t from Template t LEFT JOIN FETCH t.fieldConfig fconfig LEFT JOIN FETCH fconfig.fieldSet where t.id = :id], line 1, column 55: unexpected token [fconfig].
    

    Any thoughts on creating such a query?

  • Frédéric Gobert
    Frédéric Gobert over 12 years
    TypedQuery<Template> query = em.createQuery("SELECT t from Template t JOIN FETCH t.fieldConfig" + " JOIN FETCH t.theme" + " JOIN FETCH t.dataConfig" + " JOIN t.fieldConfig.fieldSet fs" + " JOIN t.dataConfig.textSet ts where t.id = :id", Template.class); query.setParameter("id", id); query.setHint(QueryHints.FETCH, "t.fieldConfig.fieldSet"); query.setHint(QueryHints.FETCH, "t.dataConfig.textSet"); return query.getSingleResult();