Tuesday, November 17, 2009

HibernateDaoSupport with annotations - Solved!

I've been trying to move from Spring applicationContext.xml to Spring annotations only.
One of the problems I was facing was that when I tried to move my Dao from xml to Spring annotations I got some errors.

My Dao class was defined as follows:

public class MyDaoImpl extends HibernateDaoSupport implements MyDao {
...
}

My xml configuration was -

<bean id="MyDao" class="com.myStuff.dao.impl.MyDaoImpl"
parent="daoTmpl" />

<bean id="daoTmpl" abstract="true" lazy-init="default" autowire="default"
dependency-check="default">
<property name="sessionFactory">
<ref bean="sessionFactory" />
property>
bean>


My first try was to replace the Dao definition with the Spring annotations the following way:

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;

@Repository(value = "MyDao")
@Transactional
public class MyDaoImpl extends HibernateDaoSupport implements MyDao {
...
}

But then I got an error saying that the SessionFactory was not initialized in the dao -

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

To solve this problem (i.e. to be able to use Spring annotations only and remove the Dao definition from the xml file) you should @Autowire the session factory by creating a constructor in the Dao class:

import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;

@Repository(value = "MyDao")
@Transactional
public class MyDaoImpl extends HibernateDaoSupport implements MyDao {

@Autowired
public MyDaoImpl (SessionFactory sessionFactory)
super.setSessionFactory(sessionFactory);
}

...

}

and of course, you can and should remove MyDao definition from the xml file (not the daoImpl)

Hope this helps anyone who got this problem as well

- Li

No comments:

Post a Comment