NHibernate How to make Criteria inner join without hydrating objects?

拟墨画扇 提交于 2019-12-08 06:27:59

问题


Some quick nhibernate problem:

I have sql tables:

Item { Id, Name }
ItemRange { Id, Name }
ItemHasItemRange { Id, ItemId, ItemRangeId } 

Mappings are simple, so I will not paste them, the ItemId and ItemRangeId are foreign keys, Item class has ItemHasItemRanges collection mapped as lazy bag.

I want all items which are in particular ItemRange, but I do not want to retrieve associated ItemRangeObjects, I just want to do inner join to narrow results.

When I do it like that:

c.CreateCriteria("Item", "i")
  .CreateAlias("ItemHasItemRanges", "ihpr", JoinType.InnerJoin)
  .Add(Restrictions.Eq("ihpr.ItemRange.Id", I18nHelper.CurrentItemRange.Id));

It works fine, but all ItemHasItemRange objects are fetched as well to the Item.ItemHasItemRanges collections (which is mapped as lazy)

I do not want to fetch Item.ItemHasItemRanges, because it takes time. I just want to do inner join to limit result set. It is possible in NHibernate?


回答1:


So I think that you just want to retrieve those objects in order to show an overview / list, and you are not going to actually 'do' something with those objects (unless perhaps loading one of them) ?

In that case, I think that it is better for you to work with 'projections'. Here's the scenario:

  • You'll have to create a (simple) class that just contains the properties that you want to show (where you're interested in).

  • You'll have to 'import' that class into NHibernate, so that NHibernate knows of its existence.

  • Next, you can create your Criteria statement like you have it now. (Working with your domain classes).

  • Then, you should specify how the projection should look like. That is, how the properties of your Item entity map to the properties of your 'DTO'/View class (= the simple class you just created).

  • Specify that an AliasToBean ResultTransformer should be used.

Then, execute your Criteria query. NHibernate will be able to produce the simplest possible query that is needed in order to retrieve all the data that is necessary.

I've explained something similar here




回答2:


I find out the problem was somewhere else. ItemHasItemRange table did not have multiple index on ItemId and ItemRangeId - id only had separate indexes on each field. Thats why performance was so poor.

But NHibernate question is still valid - is it possible to create inner join for criteria only to narrow results and not to fetch all joined objects which normally are lazy.



来源:https://stackoverflow.com/questions/5296461/nhibernate-how-to-make-criteria-inner-join-without-hydrating-objects

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!