tags:

views:

179

answers:

3

For mapping component in nhibernate , is there a way in the hmb file we can indicate a overlaoded constructor to be used instead of default one.

In below mapping nHibernate will use the default constructor of MyClass when reading data from database - I am wondering if we can instruct nhibernate to use a overloaded constructor instead ?

 <component name="MyProperty" class="MyClass" >
  <property name="Member1" column="member_1" />
  <property name="Member2" column="member_2" />
  <property name="Member3" column="member_3" />
</component >

Edit #1 Alternatively , does nHibernate allow to map a static value to a property instead of a column ? Something like below:

     <component name="MyProperty" class="MyClass" >
  <property name="Member1" column="member_1" />
  <property name="Member2" column="member_2" />
  <property name="Member3" **value="555"** />
</component >
A: 

The only standard way you can use constructor with parameters in NHibernate using select new HQL construct:

select new Family(mother, mate, offspr)
from Eg.DomesticCat as mother
    join mother.Mate as mate
    left join mother.Kittens as offspr

Otherwise it uses parameterless constructors for all purposes. I'm not sure whether this can be altered by hacking NHibernate internals (IClassPersister, IInterceptor, etc.)

Anton Gogolev
can we put the 'select new' HQL in hmb file ? If yes , can you scribble an example would be great! thanks.
dotnetcoder
A: 

NHibernate will always use the default constructor to instantiate an object of the type, (unless you want to create some kind of DTO and retrieve it via HQL) and then it will use the properties (or backing fields if specified) to populate the object.

If you have a type for which you do not want to expose a default (no-args) constructor, but you want to make sure that you can only instantiate the type via a specific constructor, then I always do it like this:

public class MyClass
{
    private MyClass()
    {
       // Default constructor has been made private, so it is not usable
       // by user code, but NHibernate requires a default constructor
       // (it may be private)
    }

    public MyClass( int member1, int member2, string member3 )
    {
    }
}
Frederik Gheysels
+1  A: 

Check out this post.

Darin Dimitrov
nice solution, but it requires an interceptor, which -imho- sometimes hides to much what's going on.
Frederik Gheysels