hibernate的Criteria作连表查询

Hibernater中,用Criteria作查询,如果所查询的对象PO中的属性也有一个对象PO,而且要把这个属性PO里的某个属性作为一个查询条件,则必须先为这个属性PO起一个别名!例子如下所示:有一产品表product与一产品类型表type,对应的PO为Product.java、Type.java,对应的映射文件为:Product.hbm.xml、Type.hbm.xml,映射文件如下:

<?xml version="1.0" encoding="utf-8"?><!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN""http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd"><!--     Mapping file autogenerated by MyEclipse Persistence Tools--><hibernate-mapping>    <class name="com.qhit.po.Product" table="product" catalog="test">        <id name="pid" type="integer">            <column name="pid" />            <generator class="native" />        </id>        <many-to-one name="type" class="com.qhit.po.Type" lazy="false" >            <column name="typeid" />        </many-to-one>        <property name="pname" type="string">            <column name="pname" length="50" not-null="true" />        </property>    </class></hibernate-mapping>    

<?xml version="1.0" encoding="utf-8"?><!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN""http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd"><!--     Mapping file autogenerated by MyEclipse Persistence Tools--><hibernate-mapping>    <class name="com.qhit.po.Type" table="type" catalog="test">        <id name="typeid" type="integer">            <column name="typeid" />            <generator class="native" />        </id>        <property name="typename" type="string">            <column name="typename" length="50" not-null="true" />        </property>        <set name="products" inverse="true" cascade="save-update">            <key>                <column name="typeid" />            </key>            <one-to-many class="com.qhit.po.Product" />        </set>    </class></hibernate-mapping>  

查询的例子如下所示:

Session session = HibernateSessionFactory.getSession();    Criteria cri = session.createCriteria(Product.class);    cri.createAlias("type", "b");    cri.add(Restrictions.eq("pid", 2));  cri.add(Restrictions.like("pname", "%香%"));  cri.add(Restrictions.eq("b.typeid", 2));  cri.add(Restrictions.eq("b.typename", "水果"));    List list = cri.list();  for(int i=0;i<list.size();i++){   Product p = (Product)list.get(i);      System.out.println("pid = " + p.getPid() + ":pname = " + p.getPname() + ":typeid = " + p.getType().getTypeid() + ":typename" + p.getType().getTypename());  }  session.close();

©️2020 CSDN 皮肤主题: 大白 设计师:CSDN官方博客 返回首页