3
votes

I know how to configure Spring with hibernate.

But my question is how spring and hibernate integrate and how it works.

Below is the code that I used to create Spring + Hibernate application.

<bean id="sessionFactory"
    class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean">
    <property name="dataSource">
        <ref bean="dataSource" />
    </property>
     <property name="hibernateProperties">
        <props>
            <prop key="hibernate.dialect">org.hibernate.dialect.Oracle10gDialect</prop>
            <prop key="hibernate.show_sql">false</prop>
        </props>
    </property>
</bean>

And this sessionFactory bean is injected in the java code,

import org.hibernate.SessionFactory;
public class DAOSupport extends HibernateDaoSupport {

@Autowired
public void createSessionFactory(SessionFactory sessionFactory) {
    setSessionFactory(sessionFactory);
}

As you can see that, Session Factory that I created with is associated with spring package but in code it is using hibernate package.

PS: I know HibernateDaoSupport is deprecated and this is just for understanding how both framework works.

Thanks Gimby for the link.JavaDoc

1
There is a difference, the spring class is a factory, that creates instances of the Hibernate class. - Tobb
Spring is used as an IoC, it injects SessionFactory in Hibernate, As you shown there is sessionFactory created by Spring context, not by yourself. - mlewandowski
@mlewandowski: But that sessionFactory belongs to spring package. - Lathy
@Lathy class named AbstractSessionFactoryBean super class of LocalSessionFactoryBean (which is the super class of AnnotationSessionFactoryBean) has a variable of type org.hibernate.SessionFactory and all the properties related to hiberate are stored in the LocalSessionFactoryBean. Also, spring-orm.jar( which contains mentioned FactoryBean suffixed classes) has a dependency on hibernate-core.jar - Pallav Jha

1 Answers

2
votes

Spring's AnnotationSessionFactoryBean (as well as LocalSessionFactoryBean) implements interface called FactoryBean. It has special method called Object getObject().

Whenever Spring sees, that you use the implemention of FactoryBean interface, it invokes Object getObject() method instead of creating the instance of the class itself.

In this case, SessionFactory object will be returned by the method call.

To be more specific, AnnotationSessionFactoryBean implements FactoryBean<SessionFactory> which in fact return SessionFactory object so it can be injected in Hibernate.