第一次做泛型,我在这里有点困惑。
我有以下内容:
public interface GenericDao<T, PK extends java.io.Serializable> {
/**
* Retrieve an object that was previously persisted to the database
* using the reference id as primary key
*
* @param id primary key
* @return
*/
public T read(PK id);
}
public class GenericDaoHibernateImpl<T, PK extends java.io.Serializable> implements GenericDao<T, PK>
{
private Class<T> type;
private SessionFactory sessionFactory;
/**
*
*/
public GenericDaoHibernateImpl(Class<T> type)
{
this.type = type;
}
@SuppressWarnings("unchecked")
public T read(final PK id)
{
return (T) getSession().get(type, id);
}
}
<bean id="orderDao" class="vsg.ecotrak.framework.dao.GenericDaoHibernateImpl">
<constructor-arg>
<value>vsg.ecotrak.common.order.domain.Order</value>
</constructor-arg>
<property name="sessionFactory">
<ref bean="sessionFactory"/>
</property>
</bean>
然后我的服务类只调用this.getOrderDao()。read(pId)其中pId作为Long传递给服务类的load方法。
答案 0 :(得分:2)
问题在于orderDao
的Spring声明。你编写它的方式,它将被Spring解释为
new GenericDaoHibernateImpl(Order something)
而泛型需要这样的签名(删除不必要的构造函数参数)。
new GenericDaoHibernateImpl<Order,Long>()
由于运行时类型擦除,您无法直接从Spring中推断出泛型,但您可以创建一个新类
public class OrderDao extends GenericDaoHibernateImpl<Order,Long> { }
并在Spring中引用它作为自己的bean
<bean id="orderDao" class="vsg.ecotrak.framework.dao.OrderDao">
<property name="sessionFactory"> <ref bean="sessionFactory"/>
</bean>
泛型包含在OrderDao中,只有返回基于Long PK的订单才会按预期运行。