hibernate 查询语句总结

表关系 T1oo ->ont-to-many-> T2oo (t1oo.id-t2oo.aid)

1.单条select延迟加载
        Iterator it  =  session.createQuery(" from  T1oo ").iterate();
        
while (it.hasNext()){
            T1oo t1 
=  (T1oo)it. next ();
            t1.getName();
        }
/* 运行语句 n+1
这就只加载 id
Hibernate: select t1oo0_.id as col_0_0_ from t1oo t1oo0_
此是在 t1.getName(); 延迟加载的
Hibernate: select t1oo0_.id as id0_, t1oo0_.name as name0_0_ from t1oo t1oo0_ where t1oo0_.id=?
Hibernate: select t1oo0_.id as id0_, t1oo0_.name as name0_0_ from t1oo t1oo0_ where t1oo0_.id=?
*/

2.级连查询:
1)set排序  <set ... order-by="avg desc" ...> 从大到小
2)batch-size="10" 用法是
    select * from t2oo  where aid in (?,?,?....)
3)

如果想忽略延迟,并有一定逻辑全部加载,这有两中解决办法:
1).内连
mysql >   select     *
    
->   from  t1oo t1oo0_  inner   join  t2oo t2ooset1_  on  t1oo0_.id = t2ooset1_.aid;
+----+-----------+----+-----+------+---------+
| id | name      | id | avg | aid  | version |
+----+-----------+----+-----+------+---------+
|  1 | liukaiyi  |  1 |  23 |    1 |       1 |
|  1 | liukaiyi  |  2 |  24 |    1 |       1 |
|  1 | liukaiyi  |  3 |  25 |    1 |       1 |
|  2 | liukaiyi2 |  4 |  26 |    2 |       0 |
+----+-----------+----+-----+------+---------+
 
        Iterator it  =   new  HashSet(session.createQuery( " from T1oo t1 inner join fetch t1.t2ooSet t2where t2.id<=3 " ).list()).iterator();
        
while (it.hasNext()){
            T1oo t1 
=  (T1oo)it.next();
            System.out.println(t1.getName());
            
            
for (Iterator itr = t1.getT2ooSet().iterator();itr.hasNext(); ){
                T2oo t2 
=  (T2oo)itr.next();
                System.out.println(
"    " +  t2.getAvg() );
            }
        }
结果是:
Hibernate:  select  t1oo0_.id  as  id0_, t2ooset1_.id  as  id1_, t1oo0_.name  as  name0_0_, t2ooset1_.version  as  version1_1_, t2ooset1_. avg   as  avg1_1_, t2ooset1_.aid  as  aid1_1_, t2ooset1_.aid  as  aid0__, t2ooset1_.id  as  id0__  from  t1oo t1oo0_  inner   join  t2oo t2ooset1_  on  t1oo0_.id = t2ooset1_.aid  where  t2ooset1_.id <= 3
liukaiyi
  
24
  
23
  
25

你可能感兴趣的:(hibernate 查询语句总结)