开发者

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:

  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).


Check this out, may be helpful:

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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜