`

Hibernate关联表特殊查询(多方)上

阅读更多

/**
* 多条件组合查询
*/

public List getallByMoreWhere(String name,double price){
   List list=null;
   try {
    Criteria cri=this.GetSession().createCriteria(TShop.class);
    if(name!=null && name.length()>1){
     cri.add(Restrictions.like("SName", name,MatchMode.ANYWHERE));
    }
    if(price>0){
     cri.add(Restrictions.lt("SPrice", price));
    }
    list=cri.list();
   } catch (HibernateException e) {
    throw e;
   }finally{
    this.ColseSession();
   }
   return list;
}

 
测试:

List list=shopdao.getallByMoreWhere("", 50);
   Iterator cri=list.iterator();
   while(cri.hasNext()){
    TShop shop=(TShop) cri.next();
    System.out.println(shop);
   }

 
inner join on查询
/**
* 多对一中的多方的inner join on(主对象可以查出从对象,即使主对象中关与从对象的lazy="true"也是可以把从对象查询出来)
* 以TShop为主,若TShop的TType为空,则查询后没有这条记录。即查询结果都是非空的
* 这种方式List中存放的是Object的数组,Object[]中的元素才是TShop和TType
*/

public List getallByinnerjoinTtype(){
   List list=null;
   try {
    Query query=this.GetSession().createQuery("from TShop as s inner join s.TType");
    list=query.list();
   } catch (HibernateException e) {
    throw e;
   }finally{
    this.ColseSession();
   }
   return list;
}

 

测试:
/* 多对一中的多方的inner join on(主对象可以查出从对象,即使主对象中关于从对象的lazy="true"也是可以把从对象查询出来)
   * 以TShop为主,若TShop的TType为空,则查询后没有这条记录。即查询结果都是非空的
   */

List list=shopdao.getallByinnerjoinTtype();
   Iterator iter=list.iterator();
   while(iter.hasNext()){
    Object[] obj=(Object[]) iter.next();
    TShop shop=(TShop) obj[0];
    TType type=(TType) obj[1];
    System.out.println(shop.getSName()+" "+shop.getSPrice()+" 所属类别"+shop.getTType().getTName());
    System.out.println(type.toString());
   
   }

 
   inner join fetch查询
/**
* 多对一中的多方的inner join fetch(主对象可以查出从对象,即使主对象中关与从对象的lazy="true"也是可以把从对象查询出来)
* 以TShop为主,若TShop的TType为空,则查询后没有这条记录。即查询结果都是非空的
* 这种方式List中存放的是TShop对象,TShop.TType对象是非空的
*/

public List getallByinnerjoinTtype2(){
   List list=null;
   try {
    Query query=this.GetSession().createQuery("from TShop as s inner join fetch s.TType");
    list=query.list();
   } catch (HibernateException e) {
    throw e;
   }finally{
    this.ColseSession();
   }
   return list;
}

 
测试:
/**
   * 用的from TShop as s inner join fetch s.TType
   * 这样list中存放的就是TShop对象,但它会把一方也查出来,
   * 同样如查TShop对象对应的TType为null,这个TShop也不会查询出来,即查询结果都是非空的。
   */
  

 List list=shopdao.getallByinnerjoinTtype2();
   Iterator iter=list.iterator();
   while(iter.hasNext()){
    //这样就是错的
    //Object[] obj=(Object[]) iter.next();
    //TShop shop=(TShop) obj[0];
    //TType type=(TType) obj[1];
    //System.out.println(shop.getSName()+" "+shop.getSPrice()+" 所属类别"+shop.getTType().getTName());
    //System.out.println(type.toString());
    TShop shop=(TShop) iter.next();
    System.out.println(shop.getSName()+" "+shop.getSPrice()+" 所属类别"+shop.getTType().getTName());
   
   }

 

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics