我整天用Google搜索,我找不到如何映射这类对象的好例子:
class Parent{
private Integer parentId;
private String parentName;
private List<Child> childs;
// ....... getters and setters ............
}
class Child{
private Integer childId;
private String childName;
private Parent parent;
// ....... getters and setters ...........
}
我不知道如何为这种List制作地图。
答案 0 :(得分:1)
Hibernate文档有很多examples,包括this one,这基本上就是你要找的东西。对于您的情况,XML映射将如下所示:
<class name="Parent" table="Parent">
<id name="parentId" column="id" type="integer" /> <!-- TODO: specify generator -->
<property name="parentName" type="string" column="name" />
<bag name="childs" table="Children" inverse="true">
<key column="parent_id" />
<one-to-many class="Child" />
</bag>
</class>
<class name="Child" table="Children">
<id name="childId" column="id" type="integer" /> <!-- TODO: specify generator -->
<property name="childName" type="string" column="name" />
<many-to-one name="parent" column="parent_id" not-null="true"/>
</class>
有关基于注释的映射的示例,请查看here
答案 1 :(得分:0)
首先,您应该将List<Child>
声明为IList<Child>
,因为NHibernate需要能够使用自己的实现IList的集合类型。
在地图中,您应该使用'bag'元素来映射您的List。 (您确定要使用List而不是Set吗?因为List允许单个实体在列表中出现一次以上,而Set不允许这样做。)
我应该这样做:
public class Parent
{
private IList<Child> _children = new List<Child>();
public ReadOnlyCollection<Child> Children
{
get {return _children.AsReadOnly();}
}
}
映射:
<class name="Parent" table="Parent">
<list name="Children" table="..." access="field.camelcase-underscore" inverse="true">
<key column="..." />
<one-to-many class="Child" />
</list>
</class>
(为了简洁,省略了其他属性)
(噢,现在我看到了,你正在使用Hibernate?我的代码示例是在C#中,所以我不知道你是否有ReadOnlyCollection等概念......)