Hibernate的连接查询
一.内连接
public void find(){
Session session =HibernateUtil.getSession();
List<Object []> list= session.createQuery("select c.realName,o.number from Customers as cinner join c.orders o").list();
for(Object [] L:list){
System.out.println(L[0]+" "+L[1]);
}
运行结果:Hibernate: select customers0_.realName as col_0_0_, orders1_.number ascol_1_0_ from Customers customers0_ inner join orders orders1_ oncustomers0_.id=orders1_.cid
df 2
hehe 123
结论:从运行结果中hibernate中语句中on连接,不必要在查询中写出
二.外连接
外连接分为左外连接,右外连接,自然连接
List<Object []> list= session.createQuery("select c.realName,o.number from Customers as c leftjoin c.orders o").list();
三.CriteriaQueries
public void crest(){
Session session =HibernateUtil.getSession();
List<Customers> list=session.createCriteria(Customers.class).add(Restrictions.like("realName", "d%")).list();
for(Customers l:list){
System.out.println(l.toString());
}
}
运行结果:Hibernate: select this_.id as id0_0_, this_.realName asrealName0_0_, this_.pass as pass0_0_, this_.sex as sex0_0_, this_.petName aspetName0_0_, this_.email as email0_0_, this_.rdate as rdate0_0_ from Customersthis_ where this_.realName like ?
Customers [id=2, realName=df, pass=111,sex=null, petName=null, email=null, rdate=null]
QBC主要有以下部分组成:
1. Criteria接口:代表一个查询。它是一个查询条件的容器,通过它的add()方法向其实例中添加查询条件。
2. Criterion接口:代表了一种面向对象的查询条件。
3. Restriction类:它提供了一系列的静态方法用来设定查询条件并作为
public void crest() {
Session session = HibernateUtil.getSession();
List<Customers> list = session.createCriteria(Customers.class)
.add(Restrictions.like("realName", "d%")).list();
for (Customers l : list) {
System.out.println(l.toString());
}
}
运行结果:Hibernate: select this_.id as id0_0_, this_.realName as realName0_0_,this_.pass as pass0_0_, this_.sex as sex0_0_, this_.petName as petName0_0_,this_.email as email0_0_, this_.rdate as rdate0_0_ from Customers this_ wherethis_.realName like ?
Customers [id=2, realName=df, pass=111,sex=null, petName=null, email=null, rdate=null]
四.Native SqlQueries
原生sql查询,就是直接使用标准的sql语言或者特定数据库的sql进行查询。对原生sql查询执行的控制是通过sql’query接口进行的,通过在session上调用CreatSqlquery()来获得这个接口。
public void crestnative() {
Session session = HibernateUtil.getSession();
List<Customers> list = session
.createSQLQuery("select * from customers")
.addEntity(Customers.class).list();
for (Customers l : list) {
System.out.println(l.toString());
}
}
运行结果:Hibernate: select * from customers
Customers [id=2, realName=df,pass=111, sex=null, petName=null, email=null, rdate=null]
Customers [id=3, realName=ssd,pass=111, sex=, petName=as, email=asd, rdate=null]
Customers [id=4, realName=hehe,pass=444, sex=null, petName=null, email=null, rdate=null]
Customers [id=5, realName=hehe,pass=123, sex=null, petName=null, email=null, rdate=null]
Customers [id=6, realName=hehe, pass=123,sex=null, petName=null, email=null, rdate=null]