views:

39

answers:

2

Is it possible to configure Hiberate/NHibernate not to use the default constructor to create objects when reading from the database?

When Hibernate reads 10 customers from a table, it creates 10 Customer objects. It does this by

Customer c = new Customer();

Can I tell Hibernate to do the following instead:

Customer c = ACertainStaticFactory.CreateNewCustomer();

or even to manage a factory instance:

ACertainFactory factory = .....;
Customer c = factory.CreateNewCustomer();

or even more sophisticated, to pass a parameter which I set before:

// My client code
Query query = session.CreateQuery(...);
// either:
query.SetSomeParameter(someObject);
// or:
session.SetSomeParameter(someObject);

query.List();

// Hibernate should then behave like this:
Customer c = new Customer(someObject);
// or
Customer c = ACertainStaticFactory.CreateNewCustomer(someObject);
// etc.

Is that possible in anyway? If yes: How? If no: Is there an alternative?

A: 

Check this out, may be helpful:

http://fabiomaulo.blogspot.com/2008/11/entities-behavior-injection.html

epitka
The result sounds good, still looks quite complicated compared to implement an interceptor. (Yet have to read both resources in depth yet.)
chiccodoro
+2  A: 

When Hibernate reads 10 customers from a table, it creates 10 Customer objects. It does this by (...)

More precisely, Hibernate uses Class<T>#newInstance() to create new instances of an entity, which relies on the no-arg constructor. Hence the need to provide it.

Is that possible in anyway? If yes: How? If no: Is there an alternative?

Your requirement looks close to the Possible to have Hibernate hydrate objects with Factory? thread on Hibernate's forums so I'll quote Steve's answer (updated to match current names):

This is totally doable. In fact you have two options:

  1. create a custom EntityPersister implementation;
  2. create a custom Interceptor implementation, specifically the Interceptor.instantiate() method will be of interest to you...

I think I'd go the interceptor way (not sure about your complex scenario but implementing the factory approach looks pretty easy).

Pascal Thivent
+1 Sounds exactly like what I was looking for!
chiccodoro