5.6.4 映射集合属性:Set集合属性

来源:互联网 发布:java抢票软件开发源码 编辑:程序博客网 时间:2024/06/05 07:04

我们先将test库里的表删除:

然后新建一个web工程,并编写代码:

Person.java :

public class Person {private int id;private String name;private int age;private Set<String> schools=new HashSet<String>();public int getId() {return id;}public void setId(int id) {this.id = id;}public String getName() {return name;}public void setName(String name) {this.name = name;}public int getAge() {return age;}public void setAge(int age) {this.age = age;}public Set<String> getSchools() {return schools;}public void setSchools(Set<String> schools) {this.schools = schools;}}
Person.hbm.xml :

<?xml version="1.0"?><!DOCTYPE hibernate-mapping PUBLIC     "-//Hibernate/Hibernate Mapping DTD 3.0//EN"    "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">    <hibernate-mapping package="db.domain">    <class name="Person" table="persons">            <id name="id" type="integer">            <generator class="native"></generator>        </id>        <property name="name" type="string">            <column name="name"></column>        </property>        <property name="age" type="integer">            <column name="age"></column>        </property>        <set name="schools" table="schools">            <key column="person_id" not-null="true"/>            <element type="string" column="school_name" not-null="true"/>        </set>            </class></hibernate-mapping>
Set集合属性的映射与List有点不同,因为Set是无序的,不可重复的集合,因此<set.../>元素无须使用<list-index.../>子元素来映射集合元素的索引列。<element.../>元素有个not-null属性,该属性默认为false,即该列默认可以为空。

Test.java :

public class Test {public static void main(String[] args) {Person p1=new Person();p1.setName("tom");p1.setAge(20);Set<String> schools1=new HashSet<String>();schools1.add("小学");schools1.add("初中");p1.setSchools(schools1);Person p2=new Person();p2.setName("jack");p2.setAge(23);Set<String> schools2=new HashSet<String>();schools2.add("小学");schools2.add("初中");schools2.add("高中");p2.setSchools(schools2);Session session=HibernateSessionFactory.getSession();Transaction txt=session.beginTransaction();session.save(p1);session.save(p2);txt.commit();HibernateSessionFactory.closeSession();}}
运行Test.java,查看数据库:


对比List和Set两种集合属性:List集合的元素有顺序,而Set集合的元素没有顺序。当集合属性在另外的表中存储时,List集合属性可以用关联持久化类的外键;列和集合元素索引列作为联合主键;但Set集合没有索引列,则以关联持久化类的外键和元素列作为联合主键,前提是元素列不能为空。