为什么 NHibernate 忽略 FetchMode.Join?
我有一个名为“会员”的实体。一个成员可以关注许多其他成员(根据域),因此属于多对多关系。我在数据库中创建了一个关系表(member_follows)。使用 Fluent NHibernate,我还专门使用了一个新实体“MemberFollow”来映射此关系,如下所示:
public class MemberMap : MapBase<Member>
{
public MemberMap()
: base()
{
Table("members");
Map(x => x.Id ).Column("id" );
Map(x => x.Fullname).Column("fullname");
}
public class MemberFollowMap : MapBase<MemberFollow>
{
public MemberFollowMap()
: base()
{
Table("members_follows");
Map(x => x.Id).Column("id");
References<Member>(x => x.Follower)
.Column("follower_id")
.Fetch.Join();
References<Member>(x => x.Member)
.Column("member_id");
.Fetch.Join();
}
}
由于 MemberFollow 映射的 FetchMode 设置为 Join,我希望此查询能够在一个查询中获取成员。然而,当我查看日志时,我发现 NHibernate 执行了一个简单的选择来查找每个关注成员的 ID,并在访问时一一加载成员。
public IList<Member> ListFollowings(Int32 FollwerId, Int32 Start, Int32 Size, String SortBy, SortOrder OrderBy)
{
DetachedCriteria Filter = DetachedCriteria.For<MemberFollow>();
Filter.Add (Expression.Eq("Follower.Id", FollwerId));
Filter.AddOrder (OrderBy == SortOrder.Asc ? Order.Asc(SortBy) : Order.Desc(SortBy));
Filter.SetProjection (Projections.Property("Member"));
Filter.SetFirstResult(Start);
Filter.SetMaxResults (Size );
return Find<Member>(Filter);
}
所以我的问题是:为什么 NHibernate 忽略映射类设置的 FetchMode?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我认为你可能从错误的角度来看待它。在 NHibernate 中,将多对多关系显式映射为模型对象是很不寻常的。请参阅下面的更改提案。
给定域对象
MyMember
及其覆盖的映射:以下测试通过:
正如预期的那样,生成的 SQL 依赖于内部联接:
注意: 如果,而不是仅检索每个 MyMember 的“Name”属性,您检索 MyMember 的完整实例,SQL 语句保持相同的形状。仅将额外的投影添加到 SELECT 子句中。但是,您必须修复测试才能再次通过;-)
注释 2: 如果您愿意处理拥有自己属性的多对多关系,此帖子来自凯尔·贝利和这个 可能会就此主题提供一些帮助。
注 3: 我已经尝试过:-)
给定域对象
MySecondMember
和MyFollowMap
及其覆盖的映射:以下测试通过:
正如预期的那样,生成的 SQL 依赖于内部联接:
I think you may take it from the wrong angle. In NHibernate, it is quite unusual to explicitly map a many-to-many relationship as a model object. See below a proposal for changes.
Given the domain object
MyMember
and its overriden mapping:The following test pass:
And the produced SQL relies, as expected, on inner joins:
Note: If, instead of only retrieving the "Name" property of each MyMember, you retrieve the full instances of MyMember, the SQL statement keeps the same shape. Only additional projections are added to the SELECT clause. However, you'll have to fix the test to make it pass again ;-)
Note 2: Provided you're willing to deal with a many-to-many relationship which holds properties of its own, this post from Kyle Baley and this one from the Nhibernate blog may provide some help on this subject.
Note 3: I've given it a try :-)
Given the domain objects
MySecondMember
andMyFollowMap
and their overriden mapping:The following test pass:
And the produced SQL relies, as expected, on inner joins: