NHibernate QueryOver with Fetch: Multiple SQL Queries and Database Hits Explained
When attempting to retrieve an entity and fetch a related list using NHibernate's QueryOver syntax, developers may encounter numerous redundant SQL queries and database hits. This issue arises when eager fetching is utilized.
Consider the following code:
Session.QueryOver<UserRole>() .Fetch(x => x.UsersInRole).Eager .List();
This query will result in a series of database hits, including:
This behavior stems from NHibernate's eager fetching strategy. When eager fetching is enabled, the related collection is loaded immediately along with the parent entity. However, each related object might have different associations that need to be retrieved, resulting in additional queries.
In the mapping example provided, the UserRole and UsersInRole entities have a many-to-many relationship. When eager fetching UserRoles with this relationship, the session will only contain information about the retrieved UserRole, not its associated UsersInRole.
To mitigate this issue, batch fetching should be employed. By setting the BatchSize property on the collection mapping, NHibernate will retrieve related entities in batches rather than executing individual queries for each associated object.
Solution:
HasManyToMany(x => x.UsersInRole) ... .BatchSize(25)
Assigning a batch size to both collection maps (including the class map) ensures that multiple queries are executed instead of numerous redundant ones. The exact number of queries will depend on the batch size and page size settings.
The above is the detailed content of Why Does NHibernate QueryOver with Eager Fetching Cause Multiple Database Queries?. For more information, please follow other related articles on the PHP Chinese website!