views:

701

answers:

1

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.

+3  A: 

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);
}
axtavt
awesome, thanks! I already started to go down the route of using the session factory directly, but was struggling to open transactions, I think I will just go with the DAOSupport though, as it works great for my simple purposes.
walnutmon