How to reuse named common HQL query in other named query in orm.xml

Viewed 101

I'm using HQL named queries (which are defined in XML files) to query my database using Hibernate. Some of the queries are quite complex and I find myself copy-pasting substantial parts of one query to another, similar one.

I was wondering if it's possible at all to define common parts in a "named query fragment" and reuse that fragment across all my queries?

<named-native-query name="PeriodEntity.Retail.kpiQuery.NA.dly"
                        result-class="com.abc.data.store.insight.model.PeriodEntity">
        <query>
            SELECT
                LOCATION,
                MERCHANDISE,
                PERIOD,
                ATV,
                SALES,
                sales_ly,
                COMP,
                GM,
                GM_LY,
                AUR,
                AURLY,
                UNITSALES,
                UNITSALESLY,
                UNITS_COMP,
                UPT
            FROM
                dbo.V_DLY_API_PROC_RTL_MCLT_SLS_INV v
            WHERE
                LOC_BRD_ID = :brandId
                AND chnl_key = :channelId
            ORDER BY
                time_svc_lvl_opr_id ASC
      </query>
    </named-native-query>

<named-native-query name="PeriodEntity.Retail.kpiQuery.NA.dly"
                        result-class="com.abc.data.store.insight.model.PeriodEntity">
        <query>
            SELECT
                LOCATION,
                MERCHANDISE,
                PERIOD,
                ATV,
                SALES,
                sales_ly,
                COMP,
                GM,
                GM_LY,
                AUR,
                AURLY,
                UNITSALES,
                UNITSALESLY,
                UNITS_COMP,
                UPT
            FROM
                dbo.V_Week_API_PROC_RTL_MCLT_SLS_INV v
            WHERE
                LOC_BRD_ID = :brandId
                AND chnl_key = :channelId
            ORDER BY
                time_svc_lvl_opr_id ASC
      </query>
    </named-native-query>
.
.
.
.
.
1 Answers

Since this is XML, you could use XML entities for this purpose, but I doubt this will help readability. I'd just say, live with it. That's not necessarily duplication. IMO this is like saying that spelling private final for fields is duplication. It's not.

Related