解决SSh中公共Dao使用泛型且Dao层无其他Dao,Service直接继承公共Dao,部署到tomcat可能会出现的错误。

org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'commonDao' defined in file......

Instantiation of bean failed; nested exception is org.springframework.beans.BeanInstantiationException: Could not instantiate bean class [com.zhangts.registration.dao.impl.UserDaoImpl]: Constructor threw exception; nested exception is java.lang.ClassCastException: java.lang.Class cannot be cast to java.lang.reflect.ParameterizedType


其实会犯这个错误是在CommondDaoImpl<T> extends HibernateDaoSupport implements CommonDao<T>中出现类似需要load对象的方法,比如 

public void deleteObjectByIDs(Serializable... ids){

for(int i=0;ids!=null && i<ids.length;i++){
Serializable id = ids[i];
Object object = (Object)this.getHibernateTemplate().get(entity, id);
this.getHibernateTemplate().delete(object);
}
}

实现这个方法里面,get方法需要entity.class,而这个class需要我们去转化,一般是这样去

private Class entity = (Class)GenericSuperClass.getClass(this.getClass());

GenericSuperClass这个类我们写在..util层

public class GenericSuperClass {

public static Class getClass(Class tClass) {
ParameterizedType pt = (ParameterizedType) tClass.getGenericSuperclass();
Class entity = (Class)pt.getActualTypeArguments()[0];
return entity;
}

}

这么一个项目部署在tomcat上就会报上面的错误信息。原因是在这句代码里

ParameterizedType pt = (ParameterizedType) tClass.getGenericSuperclass();

无法将java.lang.class强制转化为泛型。所以出错。


解决办法:

1. 公共Dao不使用泛型,使用  public void delete(final Object model);

2. 公共Dao使用泛型,但是需要写子Dao,每个表对应一个,该子Dao去继承这个CommonDao,就可以解决问题了(这个子Dao的内容可以是空的)

3. 只有公共Dao且使用泛型,那么将类似需要load对象的方法改写成这种样子:public T findObjectByID(Class<T> entity,Serializable id) 

这样就不会出错了

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值