HQL外连接

【例】图书与出版社

图书表

HQL外连接_第1张图片

出版社表

HQL外连接_第2张图片

1、左外连接
session=HibernateSessionFactory.getSession();
			String hql="from Book b left join b.publisherId";
			Query query=session.createQuery(hql);  
			List result=query.list();
			Iterator itor=result.iterator();
			Object [] obj=null;
			Book book=null;
			Publisher publisher=null;
			while(itor.hasNext()){
				obj=(Object [])itor.next();
				book=(Book)obj[0];
				publisher=(Publisher)obj[1];
				if(book!=null){
					System.out.print(book.getName()+"  "+book.getAuthor()
					+"  "+book.getPrice()+"  ");
				}
				if(publisher!=null){
					System.out.println(publisher.getName());
				}
			}

运行结果:

HQL外连接_第3张图片

2、右外连接
session=HibernateSessionFactory.getSession();
			String hql="from Book b right join b.publisherId";
			Query query=session.createQuery(hql);  
			List result=query.list();
			Iterator itor=result.iterator();
			Object [] obj=null;
			Book book=null;
			Publisher publisher=null;
			while(itor.hasNext()){
				obj=(Object [])itor.next();
				book=(Book)obj[0];
				publisher=(Publisher)obj[1];
				if(book==null){
					System.out.print("                                                             ");
				}
				if(book!=null){
					System.out.print(book.getName()+"  "+book.getAuthor()
					+"  "+book.getPrice()+"  ");
				}
				if(publisher!=null){
					System.out.println(publisher.getName());
				}
			}

运行结果:

HQL外连接_第4张图片

你可能感兴趣的:(hibernate)