Hibernate 集合类型使用
为了映射实体中的集合属性,Hibernate提供了set, list, array, bag, map类型。
1. set
经常使用,实体对象不重复,没有顺序。对应实体类中的java.util.Set类型。
2. list
可以记录实体插入数据库的顺序。对应实体类中的java.util.List类型。
修改Department类:
private List<Employee> employees;// Getters and setters are omitted
<class name="Department"><list name="employees" lazy="true"><key column="depart_id" not-null="true"/><list-index column="em_order"/><one-to-many name="code"><class name="Department"><bag name="employees"><key column="depart_id"/><one-to-many name="code">private Employee[] employees;
<class name="Department"><array name="employees" cascade="save-update"><key column="department_id" not-null="true"/><list-index column="emp_index" base="1"/><one-to-many name="code">private Map<String, Employee> employees;// Getters and setters are omitted
<class name="Department"><map name="employees" cascade="save-update"><key column="department_id"/><map-key type="java.lang.String" column="ind"/><one-to-many name="code">public void testMapSave() {Session s = null;Transaction tx = null;Department depart = new Department("FDI");Employee em1 = new Employee("Jacy");Employee em2 = new Employee("Neil");Map<String, Employee> employees = new HashMap<String, Employee>();employees.put(em1.getName(), em1);employees.put(em2.getName(), em2);depart.setEmployees(employees);try {s = HibernateUtil.getSession();tx = s.beginTransaction();s.save(depart);tx.commit();} catch (HibernateException e) {if (tx != null)tx.rollback();e.printStackTrace();} finally {if (s != null)s.close();}}