Search code examples
hibernatehqlcriteria

Hibernate join query without direct connection


I have following entity class

public class Customer {
    @Id
    private int id;
    @Column(name = "CID")
    private String cid;
}


public class Alccs {
    @Id
    private int vid;
//    @Column(name = "CID")
//    private String cid;

    @ManyToOne
    @JoinColumn(name = "CID", referencedColumnName = "CID")
    private Customer customer;
}


public class Rtwo {
    @Id
    private int jobNo;

    @ManyToOne
    @JoinColumn(name = "CID", referencedColumnName = "CID")
    private Customer customer;
}




public class RTwoCycle {
    @Id
    private int cycleJobNo;
    @Column
    private int vid;

    @ManyToOne
    @JoinColumn(name = "JobNo", referencedColumnName = "JobNo")
    private TblRtwo tblRtwo;

}

How do I write query like following using HQL and criteria

select top 20 * from RTwoCycle rtCycle join Alccs al on rtCycle.vid = al.vid;

For HQL I tried following

from TBLRTwoCycle rtCycle join TBLAL al on rtCycle.vid = al.vid

but getting QuerySyntaxException: Path expected for join! error

and about criteria i dont know how to do it

how to do this??


Solution

  • For HQL simple join and on clause is enough

    from table1 as t1 inner join table2 as t2 on t1.vid=t2.vid

    or

    from table1 as t1, table2 as t2 where t1.vid=t2.vid

    for criteria Restriction.sqlRestriction is the solution for this problem

    session.createCriteria(Class1,"c1")
            .createAlias("class2", "c2")
            .add(Restrictions.sqlRestriction("c1.vid=c2.vid")