Sunday, September 7, 2008

Defining DAO Objects

A little while back in an earlier blog post I mentioned a web application I've been developing which uses Hibernate Annotations and Spring MVC.

As mentioned then, the framework I'm using is based on one described in this tutorial.

In the section of this tutorial that discusses defining the DAOs (Database Access Objects) it suggests creating your DAOs using code that looks like:

<bean id="daoTmpl">
<property name="sessionFactory">
<ref bean="sessionFactory"/>
</property>
</bean>

<bean id="myObjectDao" class="org.annotationmvc.dao.MyObjectDaoTmpl" parent="daoTmpl" />

A similar pattern is repeated in a number of other locations on the internet, suggesting using a daoTmpl bean so you don't have to include the sessionFactory object individually in each one of your DAOs.

This is great advice, but in every case you get an error something like:

org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'daoTmpl' defined in ServletContext resource [/WEB-INF/bean-defs-5-dao.xml]: Instantiation of bean failed; nested exception is java.lang.IllegalStateException: No bean class specified on bean definition
Caused by:
java.lang.IllegalStateException: No bean class specified on bean definition

The problem is that you can only define a bean without a class if you declare it as abstract. To do this, change the bean definition to:

<bean id="daoTmpl" abstract="true" >
<property name="sessionFactory">
<ref bean="sessionFactory"/>
</property>
</bean>

and it will work as expected.

No comments: