Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I have Hibernate create an object through factory method?

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!

like image 688
Brian Kent Avatar asked Jun 05 '09 00:06

Brian Kent


2 Answers

This is doable using either:

  • a custom EntityPersister implementation (that you can register for a particular entity during Hibernate initialization using a custom Configuration) ~or~
  • a custom 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;
like image 154
Pascal Thivent Avatar answered Oct 21 '22 06:10

Pascal Thivent


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

like image 28
Vladimir Dyuzhev Avatar answered Oct 21 '22 07:10

Vladimir Dyuzhev