Hibernate 集合_Set_映射

在Hibernate中所支持的集合映射一共有4种:Set、List、Map和Bag
1、Set是一个接口,实例化的是其实现类,常用到实现类为HashSet、LinkedHashSet和TreeSet。Set类的特点是加入的对象不能重复,并且没有固定的顺序。
(1)、HashSet类
   HashSet类内部使用Hash算法保存元素对象,存取对象的速度比其他实现类要快,是最常用到的Set接口的实现类。
 (2)、LinkedHashSet类
   LinkedHashSet类是HashSet类的子类,内部使用链表数据结构保存数据,保存对象具有固定顺序。
 (3)、TreeSet类
   TreeSet类会排序保存的对象,被保存的对象类型需要实现Comparable接口,TreeSet按照重写的compareTo()方法的规则排序。

  Set集合映射的如用如下:
  public class User {

    private String id;
    private String username;
    private String password;
    private Set emails = new HashSet();
    
    ....
        对应的get/set方法省略

}
这里注意的是,Person类中的emails字段必须是集合类的接口类型,不能是它的具体实现,否则程序会抛出异常。
public class EMail {
   
    private String userId;
    private String emailAddress;
    public String getUserId() {
        return userId;
    }
....
        对应的get/set方法省略

}

Hibernate的配置如下:
<hibernate-mapping>
    <class name="com.kkoolerter.hibernate.beans.User" table="tb_user">
        <id name="id">
            <generator class="uuid"/>
        </id>
        <property name="username" />
        <property name="password"/>
        <set name="emails" table="tb_email">
         <key column="userid" foreign-key="id"/>
         <element type="java.lang.String" column="emailaddress"></element>
        </set>
    </class>
</hibernate-mapping>
 

你可能感兴趣的:(Hibernate,集合,set,映射,休闲)