Lesser-Known NHibernate Features: Executable HQL

var records = session.CreateQuery("update Person p set p.Email = p.Email + p.Username + '@somedomain.com' where p.Email is null").ExecuteUpdate();

What happens when you need to bulk change a lot of records on the database? The unwary novice might be tempted to load data from the database into class instances, change them and then either rely on change tracking to eventually make the changes persistent or even worse, explicitly do an update on every possibly changed entity. The non-novice readers should now rolling their eyes.

It so happens that NHibernate offers a great alternative in the form of executable HQL. Basically, it is HQL for doing bulk changes: inserts, updates and deletes.

HQL Inserts have a small gotcha: they need to come from selects. Here’s an example:

var records = session.CreateQuery("insert into Account (Name, Email, Birthday) select p.Name, p.Email, p.Birthday from Person").ExecuteUpdate();

Here is an update:

var records = session.CreateQuery("update Person p set p.Email = p.Email + p.Username + '@somedomain.com' where p.Email is null").ExecuteUpdate();

Two problems arise:

  • Cannot do joins with updates;
  • Does not update version properties.

The second one is easy to solve:

var records = session.CreateQuery("update versioned Person p set p.Email = p.Email + p.Username + '@somedomain.com' where p.Email is null").ExecuteUpdate();

Noticed the versioned keyword? This tells NHibernate to do the right thing: update the version on each affected entity, of the entity is versioned.

The final one is deletes:

var records = session.CreateQuery("delete Product p where size(p.Sales) = 0").ExecuteUpdate();

The only problem with this is that it does not cascade. You need to find another solution.

A final word on this: you can, of course, specify parameters in your queries, like in the following example.

var records = session.CreateQuery("delete Product p where p.Price = :price").SetParameter("price", 0).ExecuteUpdate();

Sessão Netponto: Entity Framework 7

A minha apresentação sobre Entity Framework 7 feita na 6ª reunião presencial da Netponto em Coimbra está disponível aqui.

Os tópicos cobertos foram:

  • Novidades do Entity Framework 7
  • Entity Framework 7 vs NHibernate

Brevemente o video e a apresentação estarão disponíveis no site da Netponto.

Obrigado a todos os que estiveram presentes! Winking smile

NHibernate Pitfalls: Sharing a Session in Multiple Threads

The NHibernate ISession is not thread-safe, that is, it shouldn’t be shared by multiple threads. The ISessionFactory, however, is thread-safe, and thus it should be used to create ISession instances as needed. Do not worry, creating sessions does not mean that connections to the database are immediately open and kept alive, the ISession implementation only opens database connections when they are necessary and closes them when they cease to be.

Lesser-Known NHibernate Features: Statistics

NHibernate makes available a number of statistics about its work; this includes, among others:

  • All of the queries executed;
  • Number of entities loaded, inserted, updated and deleted;
  • Number of optimistic concurrency misses;
  • Number of second level cache hits and misses;
  • Number of transactions started and committed;
  • Number of connections opened and closed;
  • etc.

This is available per session factory:

var statistics = sessionFactory.Statistics;

And all of these settings can be filtered per entity:

var entityStatistics = sessionFactory.Statistics.GetEntityStatistics("MyEntity");

Statistics can help us diagnose, for example, second level or query cache issues.

If we have no need for them, we can disable them before building the session factory:

cfg.SetProperty(NHibernate.Cfg.Environment.GenerateStatistics, Boolean.FalseString);

Or at runtime:

sessionFactory.Statistics.IsStatisticsEnabled = false;

An advice: do switch it off while on production, it does have an effect on performance.

Lesser-Known NHibernate Features: Dynamic Components

NHibernate, unlike others, has lots of ways to map columns from the database to and from classes. Normally, there is a 1:1 relation between columns and properties, but it doesn’t have to be so: there are, for example, components and dynamic components.

This time we will be looking at dynamic components. Dynamic components allow the usage of a dictionary, where one or several columns from the database will be stored, each in its own entry. This is pretty cool, if we need to add more columns at some point, and we do not want, or can, change the class!

Show me the code, I hear you say:

public class DataStore

{

    public DataStore()

    {

        this.Data = new Dictionary<String, Object>();

    }

 

    public virtual int Id { get; set; }

 

    public virtual IDictionary Data { get; set; }

}

Yes, it will be possible to use generic dictionaries (IDictionary<TKey, TValue>), when pull request for NH-3670 is merged, which should happen soon (NHibernate 4.1).

Now, the mappings:

var mapper = new ConventionModelMapper();

mapper.Class<DataStore>(x =>

    {

        x.Id(y => y.Id, y => { });

        x.Component(y => y.Data, new

        {

            A = 0,

            B = ""

        }, y =>

        {

            y.Property(z => z.A);

            y.Property(z => z.B);

        });

    });

I am setting the template for whatever will be stored in the Data dictionary, in this case, an integer column (A) and a string one (B) as an anonymous object. In NHibernate 4.1, it will be possible to use a dictionary instead (see NH-3704), which will help in making it more dynamic. In the third parameter to Component, we can change the mapping, for example, the physical properties of each column; we can even use ManyToOne instead of Property, so that a particular entry in the dictionary will point to another entity!

A sample usage:

session.Save(new DataStore { Data = new Dictionary<String, Object> { { "A", 1 }, { "B", "two" } } });

Lesser-Known NHibernate Features: Calculated Properties

With NHibernate you can have entity properties that are the result of a SQL expression (unlike other O/RMs). It is also possible to add arbitrary SQL restrictions to collections of an entity.

First, here’s how we define a calculated property:

public class MyEntity

{

    //rest goes here

    public Int32 ? MyCalculatedProperty { get; protected set; }

}

 

mapper.Class<MyEntity>(c =>

{

    //rest goes here

    c.Property(x => x.MyCalculatedProperty, x =>

    {

        x.Formula("(SELECT MAX(SomeTable.Something) FROM SomeTable WHERE SomeTable.Id = Id)");

        x.Insert(false);

        x.Update(false);

    });

});

NHibernate is clever enough to find out that the un-prefixed Id refers to the entity’s table. This is a silly example, but I think you get the picture. Remember that this is plain SQL, not HQL, and will not be translated in any way.

As for collection restrictions, a simple example:

public class MyEntity

{

    //rest goes here

    public virtual IEnumerable<MyIssue> RecentIssues { get; protected set; }

}

 

mapper.Class<MyEntity>(c =>

{

    //rest goes here

    c.Set(x => x.RecentIssues, x =>

    {

        c.Where("(date >= (GETDATE() - 7))");

        //rest goes here

    }, c => c.OneToMany());

});

Notice that I am mapping the RecentIssues collection as IEnumerable<T>, this is because otherwise I would have to check if the values being added matched the desired constraint (“>= GETDATE() – 7”, the last 7 days). Certainly possible, but I leave it as an exercise to you, dear reader! Of course, GETDATE() is a SQL Server function, the restrictions can only be specified in native SQL.

Stay tuned for more!

Lesser-known NHibernate Features: Filters

Unlike other OR/Ms – which, as always, shall remain unnamed – NHibernate offers a couple of ways to automatic filter results. Basically, we have two options:

  • Static restrictions;
  • Dynamic restrictions, or filters.

Because filters offer everything that static restrictions do and more, we’ll focus on filters.

A filter can specify a restriction, in terms of a SQL clause, to either an entity as a whole (the class, not a specific query) or to a collection (bag, set, list, map, array, etc).

For example, imagine you have a table that holds values that can be translated and a translation table for that purpose:

image

You will want to retrieve only the translation for the current culture. A domain model could look like:

image

We would like to apply a restriction to the Translations property of Translatable, so as to filter the translations by the current culture.

First, we need to create a filter, this is done at Configuration level:

cfg.AddFilterDefinition(new FilterDefinition("CurrentCulture", string.Empty, new Dictionary<string, IType> { { "Culture", NHibernateUtil.String } }, false));

The restriction can be defined on the filter itself, or per entity or collection. In this case, I didn’t specify it on the filter (string.Empty), so I will need to do it at the collection level:

mapper.Class<Translatable>(x =>

{

        //rest goes here

        x.Set(y => y.Translations, y =>

        {

            //rest goes here

            y.Filter("CurrentCulture", z =>

            {

                z.Condition("Culture = :Culture");

            });

        });

    }

);

A filter needs to be explicitly made active, and, if it contains parameters, all of its parameters must be set:

session.EnableFilter("CurrentCulture").SetParameter("Culture", CultureInfo.CurrentCulture.Name);

Now, whenever the Translations collection is retrieved, either through a SELECT or an INNER JOIN, the “Culture = :Culture” restriction – where, of course, :Culture is replaced by the current parameter value – will be applied automatically, together with the foreign key restriction.

The other option is to filter entities as a whole. Remember soft deletes? I wrote two posts on them (here and here). Instead of using static restrictions, we can instead use filters:

cfg.AddFilterDefinition(new FilterDefinition("SoftDeletes", "deleted = 0, new Dictionary<string, IType>(), true));

 

mapper.Class<Record>(x =>

{

    x.Filter("SoftDeletes", y => {});

    x.Set(y => y.Children, y =>

        {

            y.Filter("SoftDeletes", z => {});

        });

});

In this example, I define the restriction string on the filter itself, and I apply it to both the Record entity and its Children collection. This time, no parameters, but we still need to enable the filter before we issue a query:

session.EnableFilter("SoftDeletes");

If for any reason you want to disable a filter, it’s easy:

session.DisableFilter("SoftDeletes");

Or even get its definition:

var filter = sessionFactory.GetFilterDefinition("SoftDeletes");

Enjoy your filters!

Lesser-Known NHibernate Features: Mapping By Convention

Did you know that NHibernate, like other O/RMs out there, allows you to map classes by convention? Yes, it’s true… Smile Let me show you how!

First, you need to create an instance of the appropriately-named ConventionModelMapper:

var mapper = new ConventionModelMapper();

Next, you need to tell it where is the assembly (or assemblies) containing the entities you want to map:

var mappings = mapper.CompileMappingFor(typeof(MyEntity).Assembly.GetExportedTypes());

Finally, you need to add the generated mappings to a Configuration instance:

cfg.AddMapping(mappings);

That’s all it takes! Really! Winking smile

Granted, this is very convenient, but we don’t know much what is happening inside; for example, what id generation strategy is it using? By default, it uses native, which means it will use the native strategy of the database engine currently being used – identity for SQL Server and MySQL, sequence for Oracle and PostgreSQL, etc. If you wish to override this, you certainly can:

mapper.BeforeMapClass += (modelInspector, type, classCustomizer) =>

{

    classCustomizer.Id(x =>

    {

        x.Generator(Generators.HighLow);

    });

};

This tells the mapper to use the high-low strategy for all entities.

What if you want to change the default naming of columns and tables? Well, you have two options:

  1. Provide an handler for the BeforeMapClass or BeforeMapProperty events and in it change the name of the physical object:
    mapper.BeforeMapClass += (modelInspector, type, classCustomizer) =>

    {

        classCustomizer.Table(this.GetTableName(type.Name));

    };

    
    

    mapper.BeforeMapProperty += (modelInspector, member, propertyCustomizer) =>

    {

        propertyCustomizer.Column(this.GetColumnName(member.LocalMember.Name));

    };

  2. Provide your own implementation of INamingStrategy to NHibernate:
    public class CustomNamingStrategy : INamingStrategy

    {

        public String ClassToTableName(String className)

        {

            return className;

        }

    
    

        public String ColumnName(String columnName)

        {

            return columnName;

        }

    
    

        public String LogicalColumnName(String columnName, String propertyName)

        {

            return columnName;

        }

    
    

        public String PropertyToColumnName(String propertyName)

        {

            return propertyName;

        }

    
    

        public String PropertyToTableName(String className, String propertyName)

        {

            return propertyName;

        }

    
    

        public String TableName(String tableName)

        {

            return tableName;

        }

    }

    
    

    cfg.SetNamingStrategy(new CustomNamingStrategy());

In general, you can trust NHibernate’s judgement, but if you wish, you can override other aspects of the mapping by providing handlers to the many events of ConventionModelMapper. Say, for example, that you want to exclude (or include) only certain classes from an assembly, you can provide an handler for the IsEntity event:

mapper.IsEntity += (type, @default, assemblyName) =>

{

    return typeof(IEntity).IsAssignableFrom(type);

};

Or you want to configure a collection as a set rather than a bag:

mapper.IsBag += (member, @default) =>

{

    return false;

};


mapper.IsSet += (member, @default) =>

{

    return true;

};

Or even set a collection as not lazy and use inner join fetching:

mapper.BeforeMapSet += (modelInspector, member, propertyCustomizer) =>

{

    propertyCustomizer.Lazy(CollectionLazy.NoLazy);

    propertyCustomizer.Fetch(CollectionFetchMode.Join);

};

 

Lesser-Known NHibernate Features: LINQ Extensions

With NHibernate, you are not bound by the out-of-the box methods that LINQ provides, and their default translations to SQL. I already mentioned that you can add your own extension methods, with minimum work:

public static class StringExtensions

{

    [LinqExtensionMethod("FREETEXT")]

    public static Boolean Freetext(this String propertyName, String value)

    {

        return (propertyName.ToUpper().Contains(value.ToUpper()));

    }

}

For this example, I am creating an extension for the FREETEXT T-SQL function, which is one of the ways by which we can do full-text searching. All it takes is the LinqExtensionMethodAttribute applied to a method, with the name for the database function (can be different from the method name), and that’s it! NHibernate will try to match the parameters:

   1: var result = session.Query<MyEntity>().Where(x => x.Name.Freetext("something") == true).ToList();

Yes… Entity Framework let’s you do this… kind of… only for some functions!

Addendum

As Paulo Morgado (@paulomorgado) pointed out, line “propertyName.ToUpper().Contains(value.ToUpper())” should really be “propertyName.IndexOf(value, StringComparison.IgnoreCase)“, because it avoids string allocations and in general is much better.

Thanks, Paulo! 😉

Lesser-Known NHibernate Features: Serializing Configuration

This isn’t exactly a feature of NHibernate, but it is something that you can do with it and most people isn’t aware of.

If you have a big number of classes and mappings in your domain, adding all of them to a Configuration instance can take some time.

NHibernate allows you to serialize the Configuration instance with all the mappings that it contains so that you can deserialize it later, which can result in reduced startup time. The disadvantage is that if you change any of the mappings, you have to discard the serialized file and build a new one.

Here’s how you can do it:

var serializer = new BinaryFormatter();

 

//serialize

using (var stream = File.OpenWrite("Configuration.bin"))

{

    serializer.Serialize(stream, cfg);

}

 

//deserialize

using (var stream = File.OpenRead("Configuration.bin"))

{

    cfg = serializer.Deserialize(stream) as Configuration)

}