Hibernate映射Set
一 POJO
package example.start.set;
import java.util.HashSet;
import java.util.Set;
public class Person
{
private int id;
private String name;
private int age;
private Set classes = new HashSet();
public Person()
{
}
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 getClasses()
{
return classes;
}
public void setClasses(Set classes)
{
this.classes = classes;
}
}
二 映射文件
<?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>
<class name="example.start.set.Person" table="person">
<id name="id" column="classid">
<generator class="identity"/>
</id>
<property name="name" type="string">
<column name="name"/>
</property>
<property name="age" type="integer">
<column name="age" />
</property>
<set name="classes" table="class">
<key column="classid" not-null="true"/>
<element type="string" column="class_name" not-null="true"/>
</set>
</class>
</hibernate-mapping>
三 测试类
package example.start.set;
import java.util.HashSet;
import java.util.Set;
import org.hibernate.Session;
import org.hibernate.Transaction;
import com.HibernateSessionFactory;
public class CreateAndStorePerson
{
public static void main(String[] args)
{
Session session = HibernateSessionFactory.getSession();
Transaction tx = session.beginTransaction();
Person yeeku = new Person();
yeeku.setAge(22);
yeeku.setName("哈哈Set");
Set s = new HashSet();
s.add("数据结构");
s.add("操作系统");
yeeku.setClasses(s);
session.save(yeeku);
tx.commit();
HibernateSessionFactory.closeSession();
}
}
与List类似,但是它是没有顺序的,不需要index key