![](/img/trans.png)
[英]How to desribe in Hibernate Map<Entity, Enum> field in Entity
[英]How to map in XML List<Entity> field with hibernate
我整日用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 ...........
}
我不知道如何為這種列表制作地圖。
Hibernate文檔有很多的例子 ,包括這一次基本上是你在找什么。 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>
有關基於注釋的映射的示例,請在此處查看
首先,您應該將List<Child>
聲明為IList<Child>
,因為NHibernate需要能夠使用自己的實現IList的集合類型。
在映射中,應使用“ bag”元素來映射列表。 (您確定要使用列表而不是集合嗎?因為列表允許一個實體在列表中出現的次數多於一次,而集合則不允許這樣)。
這就是我應該怎么做:
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等概念。)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.