What does Future () mean in NHibernate?

I am new to NHibernate description for IEnumerable Future (); says the following

// Summary:
//     Get a enumerable that when enumerated will execute a batch of queries in
//     a single database roundtrip

      

Just wondering what that means, the description has nothing to do with the word "future"

+3


source to share


1 answer


The future allows two or more sql to be executed in the same backward direction if the database supports it.

It's also nearly transparent, so you'll want to use futures whenever possible. If NHibernate cannot execute queries in one reverse hop, it will execute queries in two or more, as expected.

From http://ayende.com/blog/3979/nhibernate-futures

Let's take a look at the following piece of code:



using (var s = sf.OpenSession())
using (var tx = s.BeginTransaction())
{
    var blogs = s.CreateCriteria<Blog>()
        .SetMaxResults(30)
        .List<Blog>();
    var countOfBlogs = s.CreateCriteria<Blog>()
        .SetProjection(Projections.Count(Projections.Id()))
        .UniqueResult<int>();

    Console.WriteLine("Number of blogs: {0}", countOfBlogs);
    foreach (var blog in blogs)
    {
        Console.WriteLine(blog.Title);
    }

    tx.Commit();
}

      

This code will generate two database queries. Two database queries are expensive, we can see that it took us 114ms to get data from the database. We can do better, let us tell NHibernate that he is free to optimize in any way he likes.

using (var s = sf.OpenSession())
using (var tx = s.BeginTransaction())
{
    var blogs = s.CreateCriteria<Blog>()
        .SetMaxResults(30)
        .Future<Blog>();
    var countOfBlogs = s.CreateCriteria<Blog>()
        .SetProjection(Projections.Count(Projections.Id()))
        .FutureValue<int>();

    Console.WriteLine("Number of blogs: {0}", countOfBlogs.Value);
    foreach (var blog in blogs)
    {
        Console.WriteLine(blog.Title);
    }

    tx.Commit();
}

      

Instead of accessing the database twice, we send it once, with both requests at once. The difference in speed is quite dramatic, instead of 80ms from 114ms, so we saved about 30% of the total data access time and only 34ms.

+4


source







All Articles