Reputation: 3854
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!
Upvotes: 14
Views: 6624
Reputation: 4291
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
Upvotes: 0
Reputation: 570385
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;
Upvotes: 10
Reputation: 1430
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.
Upvotes: 2
Reputation: 18336
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().
Upvotes: 3
Reputation: 87543
See Hibernate and Spring transactions - using private constructors/static factory methods, but not a solution for avoiding the "reflectively set properties or fields" part.
Upvotes: 0