今天,博主向大家介绍一下Hibernate中的连接查询

inner join(内连接) 两边符合的查出来

left outer join(左外连接) 左边符合的查出来

right outer join(右外连接) 右边符合的查出来

full join (全连接,并不常用)

首先,我们以Book实体类与Types实体类为例,两者的关联键为book.typeidtypes.id
首先是内连接的写法:

public static List<Bookview> getBookView1(){
//获取session对象
Session session=getSession();
//第二步:编写hql语句
String sql="select new libraryBook.model.Bookview(book.name,btype.name) From Books as book inner join Types as btype on book.type.id=btype.id";
//创建query接口
Query query=session.createQuery(sql);
//执行query
List<Bookview> list=query.list();
session.close();
return list;

}

HQL语法规则:

存放在一个List对象中, 

select new list(mother, offspr, mate.name)
from DomesticCat as mother
inner join mother.mate as mate
left outer join mother.kittens as offspr

直接返回一个实际的类型安全的Java对象

select new Family(mother, mate, offspr)
from DomesticCat as mother
join mother.mate as mate
left join mother.kittens as offspr
java.lang.ClassNotFoundException: Could not load requested class : Bookview

java.lang.ClassNotFoundException: Could not load requested class : Bookview
加载不到该类
在该程序中我们使用的是第二种,注意:在执行是一直提示无法加载到BOOKview类,博主先前也不懂,明明先前已经导包了,后来就在HQL语句中加上了包名,契机发生了。

接着。便是使用where进行连接,这种类似于外连接,较少用
以下是程序代码:

public static List<Bookview> getBookView(){
//获取session对象
Session session=getSession();
//第二步:编写hql语句
String sql="select new libraryBook.model.Bookview(book.name,btype.name) From Books as book , Types as btype where book.type.id=btype.id";
//创建query接口
Query query=session.createQuery(sql);
//执行query
List<Bookview> list=query.list();
session.close();
return list;

}

注意:只要采取了HQL语句的关联关系,那么之前在配置文件 中的所写关联便失效了