通用把数据库查出来的数据实体动态的赋给对象实体并返回他的结果集

/*
 * 定义一个泛型的类
 * 这个类的功能主要是
 * 把数据库查出来的实体动态的赋给实体。并返回他的结果集
 * 只要把目标对象,和数据结果集传给getEntity()就可以。
 */
public class GetEntityBean<T> {
	/*
	 * ZIDUAN 主要是用来检索该实体中的Set 方法
	 */
	public final static String ZIDUAN = "set";

	/*
	 * 这个方法就是把结果集赋给实体 然后返回一个List【很牛】
	 */
	public List<T> getEntity(T t, ResultSet re) throws SQLException {
		List<T> list = new ArrayList<T>();
		Method[] me = t.getClass().getMethods();// 得到该实体的中的所有方法
		Class prtype = null;
		/*
		 * 循环结果集把值赋给实体
		 */
		while (re.next()) {
			/*
			 * 遍历这个类中的所有方法同时给set方法赋值
			 */
			
			T t1=null;
			try {
				// 在用这个方法的时候要注意要明白是怎么回事 重点
				t1=(T) t.getClass().newInstance();
			} catch (InstantiationException e1) {
				
				e1.printStackTrace();
			} catch (IllegalAccessException e1) {
				
				e1.printStackTrace();
			}
			for (Method md : me) {
				String methodName = md.getName();
				if (!(methodName.substring(0, 3).equals(ZIDUAN))) {
					continue;
					
				}
				try {
					/*
					 * 这个主要把实体中的字段和数据库中的字段对应住
					 */
					String columnName = methodName.substring(3, 4)
							.toLowerCase()
							+ methodName.substring(4);
					/*
					 * 这个就是赋值的方法
					 */

					try {
						prtype = t.getClass()
								.getMethod("get" + methodName.substring(3),
										new Class[] {}).getReturnType();

					} catch (SecurityException e) {

						e.printStackTrace();
					} catch (NoSuchMethodException e) {

						e.printStackTrace();
					}
					if (prtype.toString().equals("int")) {
						md.invoke(t1, Integer.parseInt(re.getObject(columnName)
								.toString()));
					} else {
						md.invoke(t1, re.getObject(columnName).toString());
					}

				} catch (IllegalArgumentException e) {

					e.printStackTrace();
				} catch (IllegalAccessException e) {

					e.printStackTrace();
				} catch (InvocationTargetException e) {

					e.printStackTrace();
				}
				
			}
			
			list.add(t1);
		}
		return list;
	}

}

 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值