With LINQ to Sql, you can specify, for a given fetch, that you don't want specific child elements to be loaded (eagerly or lazily). Is this possible in NHibernate? There are times when I just want the root object and/or only part of the object graph, and I'd like to be able to specify that rather than having to write a DTO and do mapping just to get around the fact that NHibernate feels compelled to load everything if I try to serialize my object.
Thanks!
Yes, but…
The level of flexibility you have here may depend on your version of NHibernate and how you are building your query. For example, a LINQ query (here is where versioning may make a difference) is not going to give you the same flexibility as an ICriteria
or HQL query.
With the criteria API, you can call .SetFetchMode()
, passing in the property and the desired mode for that query.
NHibernate also allows you to create projections, so you can instantiate objects of unmapped types or DTOs without mapping. Of course, a projection goes only one-way; if it isn't mapped, it can't be persisted.
Everything that Jay already said, plus you can specify laziness in your mapping files... You can specify it at the class level:
<class name="Foo" lazy="true">
<!-- additional data -->
Or at the property/collection level:
<property Name="Bar" lazy="true"/>
<set Name="Bars" lazy="true"> <-- makes the collection lazy
<set Name="Bars" fetch="join"> <-- eagerly fetches child items in the collection
<set Name="Bars" fetch="select"> <-- fetches items via another select when the collection is accessed for the first time
These defaults can be overridden for specific queries and are ignored by HQL.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With