簡體   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