有没有办法在 Hibernate 中映射工厂方法(而不是让 Hibernate 调用默认构造函数并反射设置属性或字段)?
如果它不能被映射,Hibernate 是否为逐个类地创建自定义对象提供了一个钩子?
谢谢!
这是可行的:
EntityPersister
实现(您可以在 Hibernate 初始化期间使用自定义注册特定实体Configuration
)〜或〜Interceptor
实现该Interceptor.instantiate()
方法的自定义我认为拦截器方法更容易。这是的javadoc 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().
如果它不能被映射,Hibernate 是否为逐个类地创建自定义对象提供了一个钩子?
查看实体侦听器。这些仅添加了可以帮助您的注释。想想@PrePersist 或@PostLoad。
请参阅Hibernate 和 Spring transactions - using private constructors/static factory methods,但不是避免“反射设置属性或字段”部分的解决方案。
我不知道我是否完全理解您的要求,但我认为这里描述了一个解决方案(参见解决方案 4 - Hibernate 拦截器,方法 onLoad):“Domain Driven Design with Spring and Hibernate” http:// www.jblewitt.com/blog/?p=129