Class<T>在BaseDao<T>作用

本文介绍了一种使用泛型减少DAO层代码冗余的方法。通过定义BaseDao泛型类,实现了不同实体类的通用增删改查操作,提高了代码复用性。展示了如何为特定实体创建子类并获取实例。

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>),否则转换失败。

本关任务 网上购物少不了搜索功能,本关需要借助JDBC,通过对商品名或者所属类别进行模糊查询,从数据库中获取商品列表,展示到页面。 为了完成本关任务,需要了解: JDBC查询方法封装; 商品搜索相关信息介绍。 JDBC查询方法封装 为了方便JDBC操作,平台对JDBC查询方法进行了封装,封装类com.educoder.dao.impl.BaseDao。 public static <T> List<T> operQuery(String sql, List<Object> p, Class<T> cls) throws Exception { Connection conn = null; PreparedStatement pste = null; ResultSet rs = null; List<T> list = new ArrayList<T>(); conn = getConn(); try { pste = conn.prepareStatement(sql); if (p != null) { for (int i = 0; i < p.size(); i++) { pste.setObject(i + 1, p.get(i)); } } rs = pste.executeQuery(); ResultSetMetaData rsmd = rs.getMetaData(); while (rs.next()) { T entity = cls.newInstance(); for (int j = 0; j < rsmd.getColumnCount(); j++) { String col_name = rsmd.getColumnName(j + 1); Object value = rs.getObject(col_name); Field field = cls.getDeclaredField(col_name); field.setAccessible(true); field.set(entity, value); } list.add(entity); } } catch (SQLException e) { e.printStackTrace(); } finally { releaseAll(rs, pste, conn); } return list; } 例如,第一关可以使用如下方法,获取商品列表: String sql = "select * from t_goods order by salesNum desc limit 4"; List<Goods> goodsList = null; try { goodsList = BaseDao.operQuery(sql, null, Goods.class); } catch (Exception e) { e.printStackTrace(); } 商品搜索相关信息介绍 MYSQL用户名 MYSQL密码 驱动 URL root 123123 com.mysql.jdbc.Driver jdbc:mysql://127.0.0.1:3306/online_shop?useUnicode=true&characterEncoding=UTF-8&autoReconnect=true com.educoder.entity.Goods字段及方法; 字段 描述 类型 get方法 set方法 goodsId 商品Id String getGoodsId() setGo
最新发布
06-28
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值