Hibernate 集合映射实战指南
在持久层框架中,集合映射是处理一对多或多对多关系的关键。Hibernate 支持多种 Java 集合类型,它们在数据库层面的表现各有不同。理解这些差异,有助于我们写出更高效的 ORM 配置。
基础集合类型对比
根据业务需求,我们需要选择合适的集合容器。以下是几种常见类型的特性:
- Set:无序且不可重复,对应
java.util.Set。 - List:有序,允许重复,需要额外的索引列保存位置。
- Bag:无序但允许重复,不保存顺序信息,通常映射为 List。
- Map:键值对形式,无序,适合快速查找。
- Array:原生数组映射。
值类型集合示例
当集合元素是基本数据类型或字符串时,配置相对简单。以学生爱好为例:
Set 映射
<set name="hobbies" table="student_hobby">
<key column="student_id"/>
<element type="string" column="hobby_name" not-null="true"/>
</set>
这里没有索引列,因为 Set 不关心顺序。
List 映射
<list name="hobbies" table="student_hobby">
<key column="student_id"/>
<list-index column="position"/>
<element type="string" column= =/>

