Tutorial :Can I have Hibernate create an object through factory method?



Question:

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!


Solution:1

This is doable using either:

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;  


Solution:2

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


Solution:3

And if it can't be mapped, does Hibernate provide a hook for custom object creation on a class by class basis?

Check out entity listeners. These add just the annotations that will help you out. Think @PrePersist or @PostLoad.


Solution:4

See Hibernate and Spring transactions - using private constructors/static factory methods, but not a solution for avoiding the "reflectively set properties or fields" part.


Solution:5

I don't know if I exactly understood what you're asking for, but I think that a solution is described here (see solution 4 - Hibernate interceptor, method onLoad): "Domain Driven Design with Spring and Hibernate" http://www.jblewitt.com/blog/?p=129


Note:If u also have question or solution just comment us below or mail us on toontricks1994@gmail.com
Previous
Next Post »