简体   繁体   中英

How to get the Hibernate SessionFactory from org.springframework.orm.hibernate4.LocalSessionFactoryBean?

I am migrating one old legacy application to Spring. In the data access layer of current legacy code, there is one BaseDataAccessor. This data accessor provide reference of sessionFactory through one method. To meet delivery date, I have to keep this structure same, and for that I need reference of Hibernate SessionFactory in BaseDataAccessor.

I am able to get reference of org.springframework.orm.hibernate4.LocalSessionFactoryBean by implementing ApplicationContextAware, but I am unable to convert it into SessionFactory. Is there any way to do this?

Thanks

The LocalSessionFactoryBean creates a SessionFactory :

@Bean
public LocalSessionFactoryBean sessionFactory() {
    LocalSessionFactoryBean sessionFactory = new LocalSessionFactoryBean();
    sessionFactory.setDataSource(dataSource());
    sessionFactory.setPackagesToScan(new String[] { "my.packages" });
    sessionFactory.setHibernateProperties(hibernateProperties());
    return sessionFactory;
}

then you can inject the SessionFactory like his:

@Autowired
SessionFactory sessionFactory;

If you use XML configuration it should look like this:

 <bean id="dataSource"
      class="org.springframework.jdbc.datasource.DriverManagerDataSource">
    <property name="driverClassName" value="${hibernate.connection.driver.class}"/>
    <property name="url" value="${hibernate.connection.url}"/>
    <property name="username" value="${hibernate.connection.username}"/>
    <property name="password" value="${hibernate.connection.password}"/>
</bean>

<bean id="sessionFactory"
      class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
    <property name="dataSource" ref="dataSource"/>
    <property name="packagesToScan" value="com.example.mypojo"/>
    <property name="hibernateProperties">
        <props>
            <prop key="hibernate.dialect">${hibernate.dialect}</prop>
            <prop key="hibernate.current_session_context_class">thread</prop>
        </props>
    </property>
</bean>

<bean id="transactionManager"
      class="org.springframework.orm.hibernate4.HibernateTransactionManager">
    <property name="sessionFactory" ref="sessionFactory"/>
</bean>

After that you only have to inject sessionFactory bean in other xml file or with @Qualifier annotation.

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