我有一个Hibernate DAO,根据Hibernate API 3和Spring 3.x,我只使用 asessionFactory
而不是HibernateDaoSupport
+ getHibernateTemplate()
- 我希望这是一个不错的选择...... -
现在我的目标是sessionFactory
使用注释自动装配到我的 DAO 中。
在我的spring.xml
我有这个:
<context:component-scan base-package="data" />
在数据包里面我有我所有的 DAO 和服务类。
这是我的简单HibernateDao
:
@Repository
public class PersonHDAO implements PersonDAO {
private SessionFactory sessionFactory;
@Autowired
public void setSessionFactory(SessionFactory sessionFactory) {
this.sessionFactory = sessionFactory;
}
public List<Person> findAll(){
return sessionFactory.getCurrentSession().createQuery("bla bla").list();
}
}
spring.xml
我在加载过程中没有错误,但sessionFactory
仍然是null
.
我必须做什么?
编辑
这是我的sessionFactory
声明spring.xml
:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation=
"http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.0.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd">
<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<!-- <property name="driverClassName" value="org.h2.Driver" /> -->
<property name="url" value="my/db/url" />
<property name="username" value="myUsername" />
<property name="password" value="myPassword" />
</bean>
<bean id="sessionFactory" class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean">
<property name="dataSource" ref="dataSource" />
<property name="packagesToScan" value="data" />
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">org.hibernate.dialect.H2Dialect</prop>
<prop key="hibernate.current_session_context_class">thread</prop>
<prop key="hibernate.transaction.factory_class">org.hibernate.transaction.JDBCTransactionFactory</prop>
<prop key="hibernate.show_sql">true</prop>
<prop key="hibernate.hbm2ddl.auto">update</prop>
</props>
</property>
</bean>
<context:component-scan base-package="data" />
<tx:annotation-driven/>
<bean id="transactionManager" class="org.springframework.orm.hibernate3.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory" />
</bean>
</beans>
EDIT2
现在sessionFactory
不为空,但我有另一种例外:
org.springframework.beans.factory.NoSuchBeanDefinitionException: No unique bean of type [data.PersonHDAO] is defined: expected single bean but found 0:
也许意味着它找不到PersonHDAO
bean?
谢谢大家。