---
title: "hibernate学习笔记(五)"
author: "java_hanyu"
date: "2007-08-08T23:37:54Z"
tags: []
categories: ["企业架构"]
slug: "hibernate"
draft: false
lastmod: "2007-08-08T23:37:54Z"
id: 110289
url: "https://java-hanyu.iteye.com/blog/110289"
---

一、类继承关系映射

建表策略
（1）所有类建一个表 （2）只为具体类建表 （3）每个类建一个表。

只为具体类建表，使用于不使用多态的情况下，具体类之间没有继承关系时适用
需要针对每个类写映射配置文件，就和普通的单表映射的xml文件相同。
也可以使用一个xml文件来进行映射，可以通过写union-subclass标签来表现其关系
这里不能使用id生成策略中的native，而是要指定特定的生成策略。

例：

<union-subclass name="notpad" table="tpcc_notpad">
    	<property name="wight" column="wight" type="integer"/>
</union-subclass>
<union-subclass name="desktop" table="tpcc_desktop">
         <property name="LCD" column="isLCD" type="yes_no"/>
</union-subclass>


每个类建一个表，可以有效减少数据的冗余，减少字段，查询效率不很高。
正对每个类建一个表，只要写一个配置文件来进行类的映射即可
映射文件中的子类可以使用join-subclass标签来表示，并且引用父类的主键作为共享主键，就是不需要指定id生成策略
例：

<hibernate-mapping package="alan.hbn.rel.inherit" auto-import="false">

	<class name="Computer" table="tph_computer">
		
		<id name="comid" column="comid" type="long" unsaved-value="0">
			<generator class="identity"/>
		</id>
		<property name="price" column="price" type="integer"/>
		<joined-subclass name="notpad" table="tpc_notpad">
        		<key column="comid" />
        		<property name="wight" column="wight" type="integer"/>
		</joined-subclass>
        
		<joined-subclass name="Guest" table="tpc_guest">
            		<key column="comid" />
            		<property name="LCD" column="isLCD" type="yes_no"/>    
		</joined-subclass>
	</class>

</hibernate-mapping>


所有类只建一个表，查寻效率比较高，但是会产生很多空间浪费，当子类中的非空约束，就不大适用了，这是对于子类可以使用subclass标签表示。

<hibernate-mapping package="alan.hbn.rel.inherit" auto-import="false">

	<class name="Computer" table="tph_computer">
		
		<id name="id" column="id" type="long" unsaved-value="0">
			<generator class="identity"/>
		</id>
		
		<discriminator column="computer_type" type="integer"/>

		<property name="price" column="price" type="integer"/>

		<subclass name="Administrator" discriminator-value="ad">
          <property name="wight" column="wight" type="integer"/>
    </subclass>
        
    <subclass name="Guest" discriminator-value="gu">
     		 <property name="LCD" column="isLCD" type="yes_no"/>    
    </subclass>
	</class>

</hibernate-mapping>

不考虑多态时，最好是用只针对具体类建表(2个表)，而考虑多态时尽量使用所有类建一个表，只有当子类中的属性过多是才考虑每个类建一个表的策略。
二、集合映射
1、set映射
  关联对象的属性除了外键之外，只有1、2个属性，那么就可以使用set映射
  使用了set标签的element元素，不用创建关联对象就可以实现单向一对多的关联关系 
  public class Room implements Serializable{
    private int id;
    private String roomNumber;
    private Set<String> equipments = new HashSet<String>();
    private Set<Image> images = new HashSet<Image>();
  }
   
    <set name="equipments" table="equipment_set">
      <key column="roomid" foreign-key="fk_equip_room_set"/>
      <element column="description" type="string" length="128" not-null="true"/>
    </set>
    <set name="images" table="image_set">
      <key column="roomid" foreign-key="fk_img_room_set"/>
      <composite-element class="Image">
        <property name="path" column="path" type="string" length="50" not-null="true"/>
        <property name="width" column="width" type="integer" />
        <property name="height" column="height" type="integer" />
      </composite-element>    
2、map映射
  非常有用的一种集合映射
  public class Room implements Serializable{
    private int id;
    private String roomNumber;
    private Map<String, String> equipments = new HashMap<String, String>();
    private Map<String, Image> images = new HashMap<String, Image>();
  }
  
    <map name="equipments" table="equipment_map">
      <key column="roomid" foreign-key="fk_equip_room_map"/>
      <map-key column="name" type="string" length="15" />
      <element column="description" type="string" length="128" not-null="true"/>
    </map>
    <map name="images" table="image_map">
      <key column="roomid" foreign-key="fk_img_room_map"/>
      <map-key column="name" type="string" length="15" />
      <composite-element class="Image">
        <property name="path" column="path" type="string" length="50" not-null="true"/>
        <property name="width" column="width" type="integer" />
        <property name="height" column="height" type="integer" />
      </composite-element>
    </map>

三、HQL
1、query
  (1) session.createQuery("from User");                    
      session.createCriteria(User.class);
   
  (2)查询的分页显示
   query.setFirstResult(0);
   query.setMaxResult(10);
    (a) MySql
      select * from student where limite ?,?
    (b) Oracle
      select * from (select row_.* ,rownum rownum_
                  from (select student0_.id as id0_,
                        from student student0_) row)
      where rownum_ <= ?
      and rownum_ > ?                        
   
   (3)在配置文件中的query
   <query name="findByName">
       <!]>    
   </query>
                            
   session.getNamedQuery("findByName").setString("name",name);
   
   from User;   返回对象数组，不可以强转
   select u from User u;  返回对象集合，对于集合中的每个元素都可以强转成User对象
   
2、Dynamic query
   public Collection findStudents(Student student){
         StringBuffer sb = new StringBuffer("select student from Student student where student.id>-1 ");
                                             --- student.id>-1 永远为真，再添加条件的时候都用and即可，避免判断用where还是and
         if(student.getName() != null)
             sb.append("and student.name=:name"); 
         if(student.getBirthday() != null)
             sb.append("and student.birthday=:birthday"); 
         if(student.getEmail() != null)
             sb.append("and student.email=:email");  
         ……                         
   }   
   
3、QBE
   属性多时，效率高，语句少
   忽略主键、version、关系（查询当前对象）  
   与QBC结合，弥补id查询
   Example.excludeProperty("param");  --- 查询时忽略某个属性**