これらのテーブル間に双方向の関係を持たせるには、どの HBM を作成する必要がBlog
ありますか? 両方から
試しましたが、次の問題に遭遇しました(おそらく、完全に間違っていたためです):Post
many-to-one
- オブジェクト グラフを 1 つに挿入するときに一時的な永続性エラーが発生しました
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>
必要な DB 構造:
+------------------------------+
| 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) |
+--------------+---------------+