Spring 3 注释 - HibernateDaoSupport - 存储库需要会话工厂 [英] Spring 3 Annotations - HibernateDaoSupport - Repository Requires Session Factory
问题描述
我得到一个例外说:
java.lang.IllegalArgumentException:'sessionFactory' 或'hibernateTemplate' 是必需的
java.lang.IllegalArgumentException: 'sessionFactory' or 'hibernateTemplate' is required
尝试在 HibernateDaoSupport 类上使用 @Repository
注释时.错误消息很简单,为了创建存储库,它需要一个 sessionFactory.但是,我在我的 XML 中定义了一个会话工厂:
When trying to use the @Repository
annotation on a HibernateDaoSupport class. The error message is straightforward, in order to create the Repository it needs a sessionFactory. However,I have defined a session factory in my XML:
<!-- Hibernate -->
<bean id="sessionFactory" class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean">
<property name="dataSource" ref="dashDataSource" />
<property name="annotatedClasses">
<list>
<value>com.mycomp.myapp.Category</value>
</list>
</property>
<property name="hibernateProperties">
<props>
<prop key="hibernate.show_sql">true</prop>
<prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</prop>
</props>
</property>
</bean>
所以我不确定如何为存储库提供它在创建注释驱动 bean 时所需的 SessionFactory,我尝试执行以下操作:
So I'm not sure how to give the repository the SessionFactory that it requires while it's creating it's annotation driven beans, I attempted to do the following:
@Autowired
protected HibernateTemplate createHibernateTemplate(SessionFactory sessionFactory) {
return super.createHibernateTemplate(sessionFactory);
}
但这并不能解决问题,可能是因为存储库在实例化时需要该属性,而不仅仅是在执行操作时.不幸的是,我不知道如何解决这个问题,因为没有构造函数或初始化方法可以用 @Autowired 注释覆盖.
But this does not solve the problem, likely because the repository needs that property while instantiating, not just when performing an action. Unfortunately, I don't know how to get around this problem because there are no constructors or initialization methods to override with a @Autowired annotation.
我检查以确保 sessionFactory bean 正在创建并且可以自动装配,这很好.
I checked to make sure the sessionFactory bean is being created and can be Autowired, and that is fine.
推荐答案
HibernateDaoSupport
通过 setSessionFactory()
与 SessionFactory
一起提供.但是,setSessionFactory()
是 final
,因此您不能覆盖它来添加 @Autowired
注释.但是您可以将 @Autowired
应用于任意方法并从中调用 setSessionFactory()
:
HibernateDaoSupport
is supplied with SessionFactory
via setSessionFactory()
. However, setSessionFactory()
is final
, so you can't override it to add an @Autowired
annotation. But you can apply @Autowired
to the arbitrary method and call setSessionFactory()
from it:
@Autowired
public void init(SessionFactory factory) {
setSessionFactory(factory);
}
这篇关于Spring 3 注释 - HibernateDaoSupport - 存储库需要会话工厂的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!