How do i write below query in Grails either using criteria query or executeQuery?
select * from table1 as t1 left Join(select * from table2 where id=2)as t2 On t2.table1=t1.id ;
How do i write below query in Grails either using criteria query or executeQuery?
select * from table1 as t1 left Join(select * from table2 where id=2)as t2 On t2.table1=t1.id ;
Unlike SQL, in which you query tables, GORM/Hibernate queries query domain classes. Yes, it boils down to tables, but from the Criteria, WHERE, and HQL point-of-view, it's domain classes. Which is why, as Koloritnij pointed out, knowledge of the domain model is necessary for writing the query.
One difference in how SQL and GORM perform joins is that SQL joins are created on-the-fly, in the SQL itself. Whereas GORM joins are predetermined by the domain class associations. This means that in HQL you cannot join to a sub-query. You can read more about such differences here.
That being said, using your example SQL I made an assumption about your domain model:
class DomainA {
}
class DomainB {
DomainA a
}
In the domain model above, DomainB
(table2) has a uni-directional many-to-one association with DomainA
(table1). An HQL similar to your SQL is as follows:
def hql = 'SELECT a, b FROM DomainB AS b RIGHT OUTER JOIN b.a AS a WHERE b.id = :id'
The HQL can be executed like this:
def result = DomainB.executeQuery(hql, [id: 2])
Here you go (if you have Domain Classes with foreign key):
def query
query = sessionFactory.getCurrentSession().createCriteria(table2.class)
query = query.createAlias("table1", "table1Alias", CriteriaSpecification.LEFT_JOIN, Restrictions.in( 'table1Alias.id', 'table2.id'))
Restrictions.eq( "id", 2)
If not, you have to use raw SQL:
def dataSource
Sql sql = new Sql(dataSource)
sql.exequteQuery("""....""")