Feel like a geek and get yourself Ema Personal Wiki for Android and Windows
Showing posts with label NHibernate. Show all posts
Showing posts with label NHibernate. Show all posts

30 March 2010

NHibernate: SQL query error

A unittest failed with this exception from the MSSQL CE provider:
System.Data.SqlServerCe.SqlCeException: There was an error parsing the query. 
[ Token line number = 1,Token line offset = 34,Token in error = ) ].
The SQL statements are generated by NHibernate, so this was a litte bit confusing. 

Fortunately, there is logging. And an excellent viewer.

The generated SQL statement does not contain any values to INSERT. This is logically correct, because the entity class does not contain persistent properties itself: it only contains two mapped collections:
public class HL7v3InfoMap : ClassMap<HL7v3Info>
{
    public HL7v3InfoMap()
    {
        Id(x => x.Id);

        HasManyToMany(x => x.FunctioneleEenheden)
            .Access.CamelCaseField()
            .Cascade.All();

        HasManyToMany(x => x.DataTypen)
            .Access.CamelCaseField()
            .Cascade.All();
    }
}
In this case the mapping was not finished yet, so the problem solved itself when I added more properties. But I also have cases where the class does not have any persistent properties of itself, for example a class that is an abstract base class.

I don't know a better solution than adding a dummy property to the entity.

08 October 2009

Checked propertynames in NHibernate queries

Automatic renaming of a property in VS2008 won't refactor the propertynames in NHibernate config files and queries. You will find out after running the unittests, of course, but I'd rather have a compile error, or, better, have VS2008 refactor the NHibernate config and queries too.

For the NHibernate config the reasonable alternative is to use Fluent NHibernate, which uses lambda's to get the propertynames.

For the queries you have to write such a solution yourself.

I have a base class for all entities that looks like this

public Entity<T> where T : Entity<T>
{
  public static string PropertyName(Expression<Func<T, object>> e)
  {
    UnaryExpression ue = e.Body as UnaryExpression;
    MemberExpression me = (ue == null ? e.Body as MemberExpression : 
      ue.Operand as MemberExpression);
    return me.Member.Name;
  }
}
After that I can use this method to get the propertynames in queries:
Criteria.Add(Expression.Eq(
  User.PropertyName(x => x.Emailaddress), "email@example.com"));
There are disadvantages. First, using Lambda expressions is slower than using the string value. Second, this only works for public properties. Third: in VB this will look very ugly. Until now, I can live with these disadvantages.

29 September 2009

Inheritance and NHibernate.Search

I recently ran into a problem using NHibernate.Search. It is not possible to query properties of a derived class if NHibernate.Search only has access to it through a base class.
I used to have:
  [IndexedEmbedded]
  public virtual FieldType FieldType
  {
      get;
      set;
  }
The FieldType class is an abstract class from which concrete implementations derive. I wanted to index the properties of several derived classes, for example the OtherFieldType class:
public class OtherFieldType : FieldType {
  [Field]
  public virtual string Name {
      get;
      set;
  }
}
In this example, querying NHibernate.Search with "FieldType.Name:something" won't return any results. Apparently NHibernate.Search does not know it should query the concrete class implementation, OtherFieldType, for this query.

The workaround for this is to remove the IndexedEmbedded attribute from the base property and include a private field dedicated for NHibernate.Search to index and query. The private field does hold the concrete implementation:
  public virtual FieldType FieldType
  {
      get;
      set;
  }

  [IndexedEmbedded]
  private OtherFieldType OtherFieldType
  {
      get
      {
          return FieldType as OtherFieldType;
      }
  }
In this way, NHibernate.Search will know how to index and search the embedded properties. The query "OtherFieldType.Name:something" will now return the correct results.

17 September 2009

Fetchmode.Eager, but still a proxy

I just had an issue where i could not cast a property of type Proxy_blah_blah_blah to the type that it really should have been ("Patient", in this case). The issue was still there after i explicitly set the fetchmode to "Eager": NHibernate seemed to ignore the fetchmode.

In a way, it actually did ignore the fetchmode. I am not sure if this is by design. I did not look this up, but blog the cause for future reference.

The problem was that the objects which were to be loaded eagerly, were already fetched by a previous query which had fetchmode lazy for these objects. So the objects were already present in the current session as proxies. Apparently NHibernate does not re-evaluate the lazyness of the objects if another query wants these objects to be fetched eagerly. I can understand this, because it is impossible to change existing objects to another type + nhibernate obviously wants to return the same objects from the same session.

To summerize the problem:

1. a query loads objects which have a reference to Patient which has a lazy initialized property Person
2. The property Person is now a proxy, in my case the proxy of a base class of Person
3. a second query loads objects that also have a reference to Patient. The query has fetchmodes for associationpath 'Patient' = Fetchmode.Eager and for associationpath 'Patient.Person' = Fetchmode.Eager.
4. Nhibernate now in a way ignores the fetchmode properties: in nhprof the query looks good, but the returned object tree has the previously created proxy objects instead of the resolved objects.
5. Using the Person property as a Person object now fails, because it is a proxy of a base class of Person.

A solution would be to use multiple sessions. The solution i chose in this setup is to eagerly load the objects in the first query, which made sense anyway.

28 August 2009

Wrapping the NHibernate fetchmode

Configuring the NHibernate fetchmode and lazy/eager loading has two purposes: query efficiency (reduce database hits wherever possible) and preventing the dreaded LazyInitializationException. Most properties are configured for lazy loading, because this is a sensible default. This means you often have to tweak the fetchmode for particular queries in a particular way.

But combining queries and different fetchmodes scenario's will lead to a cartesian product of possibilities if used in a traditional, repository-like way.

For example:
  • IList<Author> GetAuthors()
  • IList<Author> GetAuthorsWithArticles()
  • IList<Author> GetAuthorsWithBooks()
  • IList<Author> GetAuthorsWithBooksAndArticles()
  • IList<Author> GetAuthorsByLastname(string lastname)
  • IList<Author> GetAuthorsByLastnameWithBooks(string lastname)
  • etc...

This looks like a bad design.

The solution is the Query Object pattern (here and here). This pattern wraps queries in objects.

If the query is an object, and the fetchmode can also be configured in an object-oriented way, applying fetchprofiles to a query and executing the query looks like this:
// .. get session and transaction somewhere ..

var results = 
  new AuthorsByNameQuery()
    .LastName("Adams")
    .WithBooks()
    .WithArticles()
      .List(session);

The query object wraps the criteria and fetchmode:
class AuthorsByNameQuery 
{
  internal DetachedCriteria Criteria;

  public AuthorsByNameQuery()
  {
    Criteria = DetachedCriteria.For<Author>();
  }

  public IList<Author> List(ISession session)
  {
    return Criteria
      .GetExecutableCriteria(session)
      .List<Author>();
  }

  public AuthorsByNameQuery Lastname(string lastname)
  {
    Criteria.Add(Expression.Eq("Lastname", lastname));
    return this;
  }

  public AuthorsByNameQuery WithBooks()
  {
    Criteria.SetFetchMode("Books", FetchMode.Select);
    return this;
  }
  public AuthorsByNameQuery WithArticles()
  {
    Criteria.SetFetchMode("Articles", FetchMode.Select);
    return this;
  }
}

I have been using queries and fetchprofiles this way in a few projects now and it really helps to structure the possibilities.

31 March 2009

Quickstart tutorial for NHibernate.Search

To use NHibernate.Search one has to extract the instructions from a lot of different places, which sometimes have outdated information. 
This blog post is a summary of how I was able to successfully add an NHibernate.Search-powered search function to an existing NHibernate project.

This guide assumes you have an NHibernate project and know how it works.

1. Assemblies
Add references to NHibernate.Search.dll and Lucene.Net.dll to your project. There is no official download for NHibernate.Search, you have to compile it yourself using the nhcontrib project. But you could also download the dll's I compiled on this site.

2. Configuration
Some properties have to be added to the Configuration object:
  
  'configure directory where indices are stored
  cnf.SetProperty("hibernate.search.default.directory_provider", _
    GetType(FSDirectoryProvider).AssemblyQualifiedName)
  cnf.SetProperty("hibernate.search.default.indexBase", "~/Index")
  cnf.SetProperty("hibernate.search.default.indexBase.create", "true")

  'event listeners to automagically update indices
  cnf.SetListener(NHibernate.Event.ListenerType.PostUpdate, _
    New FullTextIndexEventListener())
  cnf.SetListener(NHibernate.Event.ListenerType.PostInsert, _
    New FullTextIndexEventListener())
  cnf.SetListener(NHibernate.Event.ListenerType.PostDelete, _
    New FullTextIndexEventListener())

The direcotry where the indices are stored can be a relative path by using the ~ as the application root. This will be translated by NHibernate.Search to a real path.

3. Add search attributes to model 
  <Indexed(Index:="MyDomainClass")> _
as attribute on the class definition 

  <Field(Index.Tokenized, Store:=Store.No)> _
For searchable textfields 

  <DocumentId()> _
For the Id field.

4. Decorate the session 
Decorate the session with a full text searchable session:

Imports NHibernate.Search
[...]
session = Search.CreateFullTextSession(sessionFactory.OpenSession())

5. Convert existing data 
Often you will want existing data to be searchable. This can be done by indexing the old data once. New entries and changes will automatically be merged with the existing indices.
Here is a generic method to index existing data.

   '''
    ''' create full text index for type T
    '''
    Public Sub CreateIndex(Of T)()
      'decorate the session
      Dim fullTextSession = _
        NHibernate.Search.Search.CreateFullTextSession(Session)
      Using trans = fullTextSession.BeginTransaction()
        Dim query = fullTextSession.CreateQuery( _
          String.Concat("from ", GetType(T).Name) _
        )
        For Each thing In query.List()
          fullTextSession.Index(thing)
        Next
        trans.Commit()
      End Using
    End Sub

6. Add search to your repository (or [some layer] )
Now you can search with nhibernate! Lucene has some powerful features, but the nhibernate search in its simplest form looks like this:

  Dim query = fullTextSession.CreateFullTextQuery(Of MyDomainClass)(  _
    "MyProperty:searchterm1 OR AnotherProperty:searchword2" _
  )
 Dim results = query.List(Of MyDomainClass)

I hope this helps.