Hibernate configure how to create an object
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:
ACert开发者_StackOverflow社区ainFactory 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?
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:
- create a custom
EntityPersister
implementation;- create a custom
Interceptor
implementation, specifically theInterceptor.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).
Check this out, may be helpful:
http://fabiomaulo.blogspot.com/2008/11/entities-behavior-injection.html
精彩评论