Class<T> 泛型T简化Dao


package org.han.classt;

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

import org.han.entity.EntityDao;
import org.hibernate.Session;
import org.hibernate.cfg.Configuration;

public class ClassT<T extends EntityDao> {//ClassT<T extends EntityDao,K>多个参数

	private Class entityClass;
	
	public ClassT() {
		super();
		// TODO Auto-generated constructor stub
		entityClass=getParameterizedType(this.getClass());
	}
	/*
	 * 获得当前类的Class
	 */
	private Class getParameterizedType(Class c){
		Type type=c.getGenericSuperclass();//返回表示此 Class 所表示的实体(类、接口、基本类型或 void)的直接超类的 Type。
		ParameterizedType parametType=null;
		if (type instanceof ParameterizedType) {
			parametType=(ParameterizedType)type;//注意此处type必须是有泛型参数
		}else{
			try {
				throw new Exception("not find ParameterizedType!");
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		Type[] types=parametType.getActualTypeArguments();//返回表示此类型实际类型参数的 Type 对象的数组
		return (Class)types[0];
	}
	/*
	 * 通用通过ID获得实体类的方法
	 */
	public T getEntityById(Integer primaryKey){
		Session sess=new Configuration().configure("main.xml").buildSessionFactory().getCurrentSession();
		sess.beginTransaction();
		T t=(T)sess.get(this.entityClass, primaryKey);
		sess.getTransaction().commit();
		return t;
	}
}

        

Dao代码:

package org.han.dao;

import org.han.classt.ClassT;
import org.han.entity.Emp;

public class EmpDaoImpl extends ClassT<Emp> {

}

package org.han.dao;


import org.han.classt.ClassT;
import org.han.entity.Dept;

public class DeptDaoImpl extends ClassT<Dept> {

}
Emp、Dept直接使用ClassT的getEntityById(Integer id)获得对应的实体

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		DeptDaoImpl deptDao=new DeptDaoImpl();
		Dept d=deptDao.getEntityById(10);
		System.out.println(d.getDname());
		
		EmpDaoImpl empDao=new EmpDaoImpl();
		Emp e=(Emp)empDao.getEntityById(7369);
		System.out.println(e);
	}

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



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值