Class<T>在BaseDao<T>作用

1.BaseDao<T>

package org.hzy.dao;

import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;

public class BaseDao<T extends EntitysSuper> { //参数可以是多个<T,K>

	static Configuration config = new Configuration().configure();
	static SessionFactory fac = config.buildSessionFactory();

	private Class entityclass;

	public Session getSession() {
		return fac.getCurrentSession();
	}

	public BaseDao() {
		// TODO Auto-generated constructor stub
		this.entityclass = getParameterizedType(this.getClass());
	}

	protected Class getParameterizedType(Class clazz) {
		//返回表示此 Class 所表示的实体(类、接口、基本类型或 void)的直接超类的 Type。
		Type ty = clazz.getGenericSuperclass();
		// 得到传入进来类的父类型 //BaseDao<Dept>--org.hzy.dao.BaseDao<org.hzy.entity.Dept>
		// System.out.println(ty);
		Type[] types=null;
		if (ty instanceof ParameterizedType) {
			//注意此处ty必须是有泛型参数 , 得到当前类型的泛型 <Dept>--class org.hzy.entity.Dept
			types= ((ParameterizedType) ty).getActualTypeArguments();
		}else{  
            try {  
                throw new Exception("not find ParameterizedType!");  
            } catch (Exception e) {  
                // TODO Auto-generated catch block  
                e.printStackTrace();  
            }
		}
		// System.out.println(types[0]);
		
		// Type t=((ParameterizedType)ty).getRawType();//得到声明这个类型的类或者接口
		return (Class) types[0];
	}

	public T get_object(Integer id) {
		return (T) this.getSession().get(entityclass, id);
	}
}



2.测试,通过不同的类则返回你这个类的类型:

public class DeptImpl extends BaseDao<Dept>{
	public static void main(String[] args) {
		
		DeptImpl de=new DeptImpl();
		Transaction t=de.getSession().beginTransaction();
		System.out.println(de.get_object(10));
		t.commit();
	}
}

public class EmpImpl extends BaseDao<Emp>{
	public static void main(String[] args) {
		EmpImpl em=new EmpImpl();
		Transaction t=em.getSession().beginTransaction();
		Emp emp=em.get_object(7369);
		System.out.println(emp.getEname());
		t.commit();
	}
}

通过使用泛型T减少Dao的冗余代码,当T继承某个对象时(T extends EntityDao)限制了参数类型必须继承该对象(EntityDao),并且ClassT必须要有泛型参数(DeptDaoImpl extends ClassT<Dept>),否则转换失败。

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值