Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Spring 3 Annotations - HibernateDaoSupport - Repository Requires Session Factory

I am getting an exception saying :

java.lang.IllegalArgumentException: 'sessionFactory' or 'hibernateTemplate' is required

When trying to use the @Repository annotation on a HibernateDaoSupport class. The error message is straightforward, in order to create the Repository it needs a sessionFactory. However,I have defined a session factory in my XML:

<!-- Hibernate -->
    <bean id="sessionFactory" class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean">
        <property name="dataSource" ref="dashDataSource" />
        <property name="annotatedClasses">
            <list>
                <value>com.mycomp.myapp.Category</value>
            </list>
        </property>
        <property name="hibernateProperties">
            <props>
                <prop key="hibernate.show_sql">true</prop>
                <prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</prop>
            </props>
        </property>
    </bean>

So I'm not sure how to give the repository the SessionFactory that it requires while it's creating it's annotation driven beans, I attempted to do the following:

 @Autowired
    protected HibernateTemplate createHibernateTemplate(SessionFactory sessionFactory) {
        return super.createHibernateTemplate(sessionFactory);
    }

But this does not solve the problem, likely because the repository needs that property while instantiating, not just when performing an action. Unfortunately, I don't know how to get around this problem because there are no constructors or initialization methods to override with a @Autowired annotation.

I checked to make sure the sessionFactory bean is being created and can be Autowired, and that is fine.

like image 223
walnutmon Avatar asked Jul 12 '10 17:07

walnutmon


1 Answers

HibernateDaoSupport is supplied with SessionFactory via setSessionFactory(). However, setSessionFactory() is final, so you can't override it to add an @Autowired annotation. But you can apply @Autowired to the arbitrary method and call setSessionFactory() from it:

@Autowired
public void init(SessionFactory factory) {
    setSessionFactory(factory);
}
like image 87
axtavt Avatar answered Oct 20 '22 03:10

axtavt