我必须为哪些 HBM 编写Blog
并Post
在这些表之间建立双向关系?
我many-to-one
从双方都尝试过,但遇到了以下问题(很可能是因为我做错了):
- 将对象图插入到一个中的瞬态持久性错误
Session
。 Blog
和Post
表相互引用的外键问题。
注意:我的例子是人为的,请不要争论设计。
设计:
来源:
public class Blog
{
public virtual int Id { get; set; }
public virtual string Name { get; set; }
public virtual Comment LastComment { get; set; } // last-comment
public virtual IList<Post> Posts { get; set; }
}
public class Post
{
public virtual int Id { get; set; }
public virtual string Content { get; set; }
public virtual IList<Comment> Comments { get; set; }
}
public class Comment
{
public virtual int Id { get; set; }
public virtual string Feedback { get; set; }
public virtual Blog Blog { get; set; } //commented-on
}
HBM:
<hibernate-mapping xmlns="urn:nhibernate-mapping-2.2" assembly="Sample"
namespace="Sample">
<class name="Blog">
<id name="Id">
<generator class="hilo" />
</id>
<property name="Name" />
<!-- How to map Comment? -->
<bag name="Posts">
<key column="BlogId" />
<one-to-many class="Post" />
</bag>
</class>
<class name="Post">
<id name="Id">
<generator class="hilo" />
</id>
<property name="Feedback" />
<bag name="Comments">
<key column="PostId" />
<one-to-many class="Comment" />
</bag>
</class>
<class name="Comment">
<id name="Id">
<generator class="hilo" />
</id>
<property name="Comment" />
<!-- How to map back to Blog? -->
</class>
</hibernate-mapping>
所需的数据库结构:
+------------------------------+
| Blog |
+--------------+---------------+
| Id | int |
| Name | nvarchar(50) |
| LastCommentId| int (null) |
+--------------+---------------+
+------------------------------+
| Post |
+--------------+---------------+
| Id | int |
| BlogId | int |
+--------------+---------------+
+------------------------------+
| Comment |
+--------------+---------------+
| Id | int |
| PostId | int |
| BlogId | int (not-null)|
| Feedback | nvarchar(200) |
+--------------+---------------+