繁体   English   中英

使用spring 3和hibernate 4 autowire hibernate session

[英]autowire hibernate session with spring 3 and hibernate 4

我想这样做: @Autowire Session session 对于hibernate 3, 此处描述该过程。 它使用... hibernate3.SessionFactoryUtils.getSession。 但是在3.2版本中,hibernate4.SessionFactoryUtils中没有这样的方法

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM