开发者

Optimization of nested entities in nhibernate

I'm developing an application where users can design custom forms for data input.

I'd like to know how to load data with nhibernate with as few database requests as possible?

My Domain Model:

They are four entities;

FormProfile - Title, description, creation date etc.

FieldGroup -Fieldsets with title and other properties

FormField -Each "row" in the fieldgroup, ex "Zip & Area"

FieldProperty -Each input/select/radiob开发者_StackOverflowutton on the FormField row. Ex. Textboxes for Zip & Area

A form structure usually looks something like this:

  • FormProfile
    • FieldGroup
      • FormField
        • FieldProperty
    • FieldGroup
      • FormField
        • FieldProperty
        • FieldProperty

What is the best way to load a FormProfile with all child items avoiding as many roundtrips to db as possible?


The best way IMO is to use the batch-size attribute in your collections.

I'm going to assume your FormProfile class has a FieldGroups collection, which have a FormFields collection, which have a FieldProperties collection.

Set batch-size to a reasonable number (say, 20), which will be the number of collections to query at once.

This way, when you get and navigate a FormProfile, you'll have just 3 additional queries (one for each collection type). These queries are small and fast (they hit only one table each, and will use an index seek on the FK if you defined one), which is usually better than having a big, denormalized query.

You can also enable second-level caching on the entities and collections, for even better performance.


Two methods spring to mind:

  • Use cacheing, so you only load the objects the first time they are requested
  • Use eager fetching, which will create SQL statements that use outer joins to pull children records in the same query as their parent.

NHibernate provides a second level cache, which is persistant per SessionFactory (unlike the regular first level cache, which is only persistant per Session).

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜