简体   繁体   中英

HIbernate many to one join criteria query

I have table1 with key_column as primary key. Table2 has key_column from table1 as foreign key. table2 has many to one relationship to table1.

I want to run a join query.

Select table1.*, table2.* from table1, table2 where table2.id = ?
    table2.some_column_other_than_key_column = ? 
    and table1.key_column = table2.key_column

<class name="tbl2class" table="tbl2" lazy="false">
   <many-to-one name="tbl1class" column="key_column"
        class="tbl1Class"
        cascade="none" lazy="false" fetch="join" update="false" insert="true" />

</class>

List<tbl2Class> tbl2List= getSession().createCriteria(tbl2Class.class)
            .add(Restrictions.eq("id", id))
            .add(Restrictions.eq("tbl1.someColumnOtherThanKeyColumn", messageType))
            .add(Restrictions.or(categoryRestriction, strategyRestriction))
            .list();

I get an exception mentiontiong Could not resolve tbl1.someColumnOtherThanKeyColumn - Why - What am I doing incorrectly.

public class Tbl1Class 
{
    private Tbl2Class tbl2Class
}

You should use something like this

Criteria tbl2Criteria = getSession().createCriteria(tbl2Class.class);
tbl2Criteria.add(Restrictions.eq("id", id));
Criteria tbl1Criteria = tbl2Criteria.createCriteria("tbl1Class");//assuming thats the name of the tbl1 instance in tbl2 class
tbl1Criteria.add(Restrictions.eq("someOtherThanKeyColumn", messageType));
tb12Criteria.add(Restrictions.or(categoryRestriction, strategyRestriction));
List<tbl2Class> result = tbl2Criteria.list();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM