![](/img/trans.png)
[英]Proper way to autowire a Hibernate Session in a Spring Transaction JUnit test
[英]autowire hibernate session with spring 3 and hibernate 4
Spring3.x发生了很大的变化,几天前我遇到了同样的问题,通过官方文档我们知道Spring不再提供HibernateTemplate和HibernateDaoSupport,我们建议使用Hibernate纯API,关于你的这里的困惑是我的解决方案:
首先,在applicationContext.xml中定义一个sessionFactory bean,
<!-- sessionFactory -->
<bean id="sessionFactory"
class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
<property name="packagesToScan">
<list>
<value>com.bbs.*.entity</value>
</list>
</property>
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">
${hibernate.dialect}
</prop>
<prop key="hibernate.show_sql">${hibernate.show_sql}</prop>
<prop key="hibernate.format_sql">${hibernate.format_sql}</prop>
<prop key="hibernate.connection.autocommit">${hibernate.connection.autocommit}</prop>
<prop key="hibernate.connection.url">jdbc:mysql://localhost/bbs</prop>
<prop key="hibernate.connection.driver_class">com.mysql.jdbc.Driver</prop>
<prop key="hibernate.connection.username">root</prop>
<prop key="hibernate.connection.password">123456</prop>
</props>
</property>
<property name="dataSource">
<ref bean="dataSource" />
</property>
</bean>
然后,在你的DAO中
@Autowired
@Qualifier("sessionFactory")
private SessionFactory sessionFactory;
public Session getSession() {
return sessionFactory.getCurrentSession();
}
通过这种方式你将获得hibernate会话,然后做你想要的,只是享受它:)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.