Is there a way to map a factory method in Hibernate (as opposed to having Hibernate call a default constructor and reflectively set properties or fields)?
And if it can't be mapped, does Hibernate provide a hook for custom object creation on a class by class basis?
Thanks!
This is doable using either:
EntityPersister
implementation (that you can register for a particular entity during Hibernate initialization using a custom Configuration
) ~or~Interceptor
implementing the Interceptor.instantiate()
method I think the Interceptor approach is easier. Here is the javadoc of the Interceptor.instantiate()
:
/**
* Instantiate the entity class. Return <tt>null</tt> to indicate that Hibernate should use
* the default constructor of the class. The identifier property of the returned instance
* should be initialized with the given identifier.
*
* @param entityName the name of the entity
* @param entityMode The type of entity instance to be returned.
* @param id the identifier of the new instance
* @return an instance of the class, or <tt>null</tt> to choose default behaviour
*/
public Object instantiate(String entityName, EntityMode entityMode, Serializable id) throws CallbackException;
Take a look at UserType. You'd need to call your factory in nullSafeGet() and populate all the fields yourself though. Reverse work is done in nullSafeSet().
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With