19 mar 2008

QueryOnlyNeededData hiberante

 

public void QueryOnlyNeededData()
{
ISession session = NHibernateSessionFactory.OpenSession();
ICriteria criteria = null; IList result = null; string buffer = null;

// get all sales when querying products we will hit the N+1 select problem
criteria = session.CreateCriteria(typeof(Sale));
result = criteria.List();

// because product.Supplier is mapped as fetch=join the select issued
// for each product will join with the supplier table
foreach (Sale s in result) buffer = s.Product.Name;

// get all sales with the product (no N+1 problem, also don't need supplier so don't get it)
criteria = session.CreateCriteria(typeof(Sale))
.SetFetchMode("Product", FetchMode.Join)
.SetFetchMode("Product.Supplier", FetchMode.Select);
result = criteria.List();

// this cycle will not issue any additional select statements
foreach (Sale s in result) buffer = s.Product.Name;
Program.ListResult("ICriteriaSamples.QueryOnlyNeededData", result);
}

FeedCount

analytics

 
sfrede