Hibernete 配置及 HQL 语法查询

http://hi.baidu.com/leyoochina/item/04dd868d93f8b98f4414cffb


http://blog.sina.com.cn/s/blog_825bd5620100zalu.html


Hibernate中outer-join、lazy 、fetch join关键字的使用:http://hi.baidu.com/xizenyin/item/78e0e0f545a69ecf521c266a

2009-05-22 11:34

Hibernate中outer-join、lazy 、fetch join关键字的使用

关键字: outer-join lazy fetch join

1、outer-join关键字(many-to-one的情况)

outer-join关键字有3个值,分别是true,false,auto,默认是auto。
true: 表示使用外连接抓取关联的内容,这里的意思是当使用load(OrderLineItem.class,"id")时,Hibernate只生成一条SQL语句将OrderLineItem与他的父亲Order全部初始化。

select * from OrderLineItem o left join Order p on o.OrderId=p.OrderId   where o.OrderLineItem_Id=?

false:表示不使用外连接抓取关联的内容,当load(OrderLineItem.class,"id")时,Hibernate生成两条SQL语句,一条查询OrderLineItem表,另一条查询Order表。这样的好处是可以设置延迟加载,此处要将Order类设置为lazy=true。

select * from OrderLineItem o where o.OrderLineItem_Id=?
select * from Order p where p.OrderId=?

auto:具体是ture还是false看hibernate.cfg.xml中的配置

注意:如果使用HQL查询OrderLineItem,如 from OrderLineItem o where o.id='id',总是不使用外部抓取,及outer-join失效。

2、outer-join(集合)

由于集合可以设置lazy="true",所以lazy与outer-join不能同时为true,当lazy="true"时,outer-join将一直是false,如果lazy="false",则outer-join用法与1同

3、HQL语句会将POJO配置文件中的关联一并查询,即使在HQL语句中没有明确join

4、In HQL, the "fetch join" clause can be used for per-query specific outer join fetching. One important thing many people miss there, is that HQL queries will ignore the outer-join attribute you specified in your mapping. This makes it possible to configure the default loading behaviour of session.load() and session.get() and of objects loaded by navigating relationship. So if you specify

and then do MyObject obj = session.createQuery("from MyObject").uniqueResult();
obj.getMySet().iterator().next();

you will still have an additional query and no outer-join. So you must explicily request the outer-join fetching:

MyObject obj = session.createQuery(
"from MyObject mo left join fetch mo.mySet").uniqueResult();
obj.getMySet().iterator().next();

Another important thing to know is that you can only fetch one collection reference in a query. That means you can just use one fetch join. You can however fetch "one" references in addition, as this sample from the Hibernate Docs demonstrates:

from eg.Cat as cat
inner join fetch cat.mate
left join fetch cat.kittens

We have once considered lifting this limitation, but then decided against it, because using more than one fetch-join would be a bad idea generally: The generated ResultSet becomes huge and is a major performance loss.

So alltogether the "fetch join" clause is an important instrument Hibernate users should learn how to leverage, as it allows tuning the fetch behaviour of a certain use case.

5、join fetchjoin 的区别

如果HQL使用了连接,但是没有使用fetch关键字,则生成的SQL语句虽然有连接,但是并没有取连接表的数据,还是需要单独的sql取数据,也就是 select a,b,d...中没有连接表的字段

6、如果集合被声明为lazy=true,在HQL中如果显式的使用 join fetch 则延迟加载失效。

7、在one-to-many的one端显式设置fecth="join",则无论如何都采取预先抓取(生成一个SQl),延迟加载失效(生成两个SQL)

8、many-to-one的延迟加载是在配置文件的class标签设置 lazy="true",one-to-many和many-to-many的延迟加载是在set标签中设置lazy="true"。而one-to- one不只要在calss标签设置lazy="true",而且要在one-to-one标签中设置constrained="true".



lazy:与之关系关键词(fetch:只用在left join 与 inner join 中) ex: from a left join fetch a.b as b (on 省略以在hbm.xml配置好),是否(及时加载 延迟加载 预加载)关联对象数据


在“一”方 ......   在“多”方


inverse:

一对多时(一个班级有多个学生),一般inverse="true",减少update,由多个员工认识老板容易;

              多对一(多个学生属于一个班级),默认值inverse="false"


多对多:

 不是外键关联


一对一:


  1. xml version="1.0"?>  
  2.     "-//Hibernate/Hibernate Mapping DTD 3.0//EN"  
  3.     "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">  
  4. <hibernate-mapping package="com.reiyen.hibernate.domain">  
  5.     <class name="IdCard" table="id_card">  
  6.         <id name="id">  
  7.               
  8.             <generator class="foreign">  
  9.                 <param name="property">personparam>  
  10.             generator>  
  11.         id>  
  12.         <property name="authorizeDate" column="authorize_date" />  
  13.         
        
        
             table="join_nn_sx"
             cascade="all">
            
            
            
            
                          class="com.lavasoft.sx._n_n.Addressnn_sx"/>
        
    
 
    
           table="ADDRESS_nn_sx">
        
            
        
        
        
        
             inverse="true"
             table="join_nn_sx">
            
            
            
                          class="com.lavasoft.sx._n_n.Personnn_sx"/>
        
    
 
六、测试方法
 
public class Test_nn_sx {
    public static void main(String[] args){
        Addressnn_sx add1=new Addressnn_sx();
        Addressnn_sx add2=new Addressnn_sx();
        Personnn_sx p1=new Personnn_sx();
        Personnn_sx p2=new Personnn_sx();
 
        add1.setAddressdetail("郑州市经三路");
        add2.setAddressdetail("合肥市宿州路");
        p1.setName("wang");
        p1.setAge(30);
        p2.setName("zhang");
        p2.setAge(22);
 
        p1.getAddresses().add(add1);
        p1.getAddresses().add(add2);
        p2.getAddresses().add(add2);
        add1.getPersons().add(p1);
        add2.getPersons().add(p1);
        add2.getPersons().add(p2);
 
 
        Session session= HibernateUtil.getCurrentSession();
        Transaction tx=session.beginTransaction();
        session.save(p1);
        session.save(p2);
//        session.saveOrUpdate(add1);
//        session.saveOrUpdate(add2);
        tx.commit();
        HibernateUtil.closeSession();
    }
}
 
七、测试结果
 
1) :正常保存.
        session.save(p1);
        session.save(p2);
//        session.saveOrUpdate(add1);
//        session.saveOrUpdate(add2);
 
  Hibernate: insert into PERSON_nn_sx (name, age) values (?, ?)
  Hibernate: insert into ADDRESS_nn_sx (addressdetail) values (?)
  Hibernate: insert into ADDRESS_nn_sx (addressdetail) values (?)
  Hibernate: insert into PERSON_nn_sx (name, age) values (?, ?)
  Hibernate: insert into join_nn_sx (personid, addressid) values (?, ?)
  Hibernate: insert into join_nn_sx (personid, addressid) values (?, ?)
  Hibernate: insert into join_nn_sx (personid, addressid) values (?, ?)



在本小节中举一些.hbm.xml映射文件的例子,让开发人员对其有一个感性的认识。接下来讲述一个用户表(tbl_user)、用户与角色关联表(tbl_user_role)、角色表(tbl_role)以及组织表(tbl_organization)的例子。

(1)tbl_user

"-//Hibernate/Hibernate Mapping DTD 3.0//EN"

"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd" >

(2)tbl_organization

"-//Hibernate/Hibernate Mapping DTD 3.0//EN"

"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd" >

(3)tbl_user_role

"-//Hibernate/Hibernate Mapping DTD 3.0//EN"

"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd" >

(4)tbl_ role

"-//Hibernate/Hibernate Mapping DTD 3.0//EN"

"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd" >




你可能感兴趣的:(hql,Hibernate)