public class GenericDao <T, PK extends Serializable> {
private final Class<T> type;
@Resource(name = "sessionFactory")
private SessionFactory sessionFactory;
public GenericDao(final Class<T> type) {
this.type = type;
}
public PK save(final T o) {
return (PK) sessionFactory.getCurrentSession().save(o);
}
// ... get,delete, etc
App context bean:
<bean id="fooDao" class="com.mycompany.dao.GenericDao">
<constructor-arg>
<value>com.mycompany.Foo</value>
</constructor-arg>
</bean>
And in service layer invoke like so :
@Autowired
private GenericDao<Foo, Integer> fooDao;
...
public doStuffIncludingSave(Foo foo)
fooDao.save(foo);
I think your solution is fine but you do not need the class parameter
T. It just limits you and does not allow to re-use the same DAO for Integers and Strings (for example).Save method does not need this type at all.
Methods like
get()orfind()should receive generic type themselves:public <T> T findById(Class<T> clazz, Serializable id);public <T> List<T> listAll( Class<T> clazz );