简体   繁体   中英

autowire hibernate session with spring 3 and hibernate 4

I want to do: @Autowire Session session . For hibernate 3, the process is described here . it uses ...hibernate3.SessionFactoryUtils.getSession. but in spring 3.2 there is no such method in ...hibernate4.SessionFactoryUtils

Great changes have taken place in Spring3.x, a few days ago I met the same problem, Through the offical document we know that Spring won't provide HibernateTemplate and HibernateDaoSupport any longer, we are advised to use Hibernate pure API, and about your confusion here is my solution:

first, define a sessionFactory bean in applicationContext.xml,

<!--  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>

and then, in your DAO

@Autowired
@Qualifier("sessionFactory")
private SessionFactory sessionFactory;

public Session getSession() {
    return sessionFactory.getCurrentSession();
}

in this way you'll get the hibernate session, then do what you want, just enjoy it:)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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