Set
HashSet 无序,不重复

List
有序,可重复

Map
HashMap 无序,不重复(以key为准)

数组

e_user e_user_addressSet
id userId
name address
要说明的信息:
a:集合表的名称(集合表)
b:集合表中的外键(集合外键)
c:集合表中的元素列(集合元素)


<?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="cn.itcast.e_hbm_collection">
<!-- 类名 -->
<class name="User" table="e_user">
<id name="id" type="integer" column="id_">
<generator class="native" />
</id>
<property name="name" type="string" column="name_" />
<!-- addressSet属性,Set集合 -->
<set name="addressSet" table="e_user_addressSet">
<key column="userId"></key>
<element type="string" column="address_"></element>
</set>
</class>
</hibernate-mapping>


package cn.itcast.e_hbm_collection;

import java.util.HashSet;
import java.util.Set;

public class User {
private Integer id;
private String name;
private Set<String> addressSet = new HashSet<String>();// Set集合

public Integer getId() {
return id;
}

public void setId(Integer id) {
this.id = id;
}

public String getName() {
return name;
}

public void setName(String name) {
this.name = name;
}

public Set<String> getAddressSet() {
return addressSet;
}

public void setAddressSet(Set<String> addressSet) {
this.addressSet = addressSet;
}

}


package cn.itcast.e_hbm_collection;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;
import org.junit.Test;

public class App {
private static SessionFactory sessionFactory = new Configuration()//
.configure()//
.addClass(User.class)//
.buildSessionFactory();

@Test
public void testSave() throws Exception {
Session session = sessionFactory.openSession();
Transaction tx = null;
try {
tx = session.beginTransaction();
// ------------------------------------
// 操作
// Set<String> set = new HashSet<String>();
// set.add("骆家庄东苑");
// set.add("文一新西路");

// 构建对象
User user = new User();
user.setName("李四");
user.getAddressSet().add("新青年厂场");
user.getAddressSet().add("新塘路");

// 保存
session.save(user);
// ------------------------------------
tx.commit();
} catch (RuntimeException e) {
tx.rollback();
throw e;
} finally {
session.close();
}
}

@Test
public void testGet() throws Exception {
Session session = sessionFactory.openSession();
Transaction tx = null;
try {
tx = session.beginTransaction();
// ------------------------------------

// 获取数据
User user = (User) session.get(User.class, 2);

// 显示信息
System.out.println(user.getId());
System.out.println(user.getName());
for (String s : user.getAddressSet()) {
System.out.println(s);
}

// ------------------------------------
tx.commit();
} catch (RuntimeException e) {
tx.rollback();
throw e;
} finally {
session.close();
}
}
}