Search code examples
javamysqlhibernategrailsgrails-orm

Add =value in a left join clause using execute query


Working with grails 3.3.8 and Mysql DB 5.5.x version. I have done this query:

 String query = $/
            select new Map( i1.id as id,i1.name as name)
            from CustomerComposition as c1
            inner join c1.instrument as i1
            left join i1.analisys as a1,
            Instrument as i2
            left join i2.analisys as a2,
            Instrument as i3
            left join i3.analisys as a3
            where 
            i1.id=i2.id and i1.id=i3.id and
            c1.portfolio.id=:ptfId and a1.phase.id=:p1Id and a2.phase.id=:p2Id and a3.phase.id=:p3Id 
        /$

        List composition = CustomerComposition.executeQuery(query,
                [ptfId: ptfId, p1Id: phase[0], p2Id: phase[1], p3Id: phase[2]])

The left join doesn't work. Then I realize that it doesn't work because I put a clause inside the WHERE. I double check with simple SQL statment and indeed it works once moved the conditional out the where. A simple snip taken just for clarification, before and it did not work:

SELECT
instrument1_.id
FROM
    customer_ptf_composition customerpt0_
    INNER JOIN instrument instrument1_ ON customerpt0_.instrument_id = instrument1_.id
    LEFT JOIN analisys analisys4_ ON instrument1_.id = analisys4_.instrument_id

WHERE
customerpt0_.portfolio_id =1216 
    AND analisys4_.phase_id =111

and after and it works due to how left/right join works:

SELECT
instrument1_.id
FROM
    customer_ptf_composition customerpt0_
    INNER JOIN instrument instrument1_ ON customerpt0_.instrument_id = instrument1_.id
    LEFT JOIN analisys analisys4_ ON instrument1_.id = analisys4_.instrument_id AND analisys4_.phase_id =111 

WHERE
customerpt0_.portfolio_id =1216

Now my question is how can I put the "and field=value" next to the left join in GORM?


Solution

  • You can use the WITH clause to achive this:

    left join i3.analisys a3 WITH a3.something = :someValue
    

    See also: current Hibernate user guide: HQL explicit join