Can I have Hibernate create an object through factory method?

情到浓时终转凉″ 提交于 2019-12-18 12:58:12

问题


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!


回答1:


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;



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




回答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.




回答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.




回答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



来源:https://stackoverflow.com/questions/953800/can-i-have-hibernate-create-an-object-through-factory-method

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!