从数据库中提取数据并注入到对象中

1.在类DBHelper中,使用方法finds查询数据,并注入到对象中

//将数据库的值注入到对象中
	public <T> List<T> finds(String sql,Class<T> c,Object ...params) {
		List<T> list=new ArrayList<T>();
		ResultSet rs=null;
		Connection con=null;
		PreparedStatement pstmt=null;
		ResultSetMetaData rsmd=null;
		try {
			con=this.getConnection();
			pstmt=con.prepareStatement(sql);
			this.setValue(pstmt, params);
			rs=pstmt.executeQuery();
			rsmd=rs.getMetaData();
			
			int colCount=rsmd.getColumnCount();//获取列数
			String[] colNames=this.getColName(rsmd, colCount);//获取所有列名
			
			List<Method> methods=this.getSetter(c);//取出给定类的所有setter方法
			T t=null;
			String colName=null;//数据库的列名
			String mName=null;//方法名称
			Object obj=null;
			String typeName=null;//类型名称
			while (rs.next()) {//每循环一次就是一条记录,对应一个对象
				t=c.newInstance();//相当于实例了一个c对象 new userInfo()
				for(String col:colNames){
					colName="set"+col;
					for(Method method:methods){
						mName=method.getName();//取出set方法名 如setUsid
						if(colName.equalsIgnoreCase(mName)){//找到了对应的方法
							obj=rs.getObject(col);//取出这个列的属性
							if(obj!=null){//如果不为空,则获取这个对象的类型,如果为空,则属性为空,不需要管
								typeName=obj.getClass().getSimpleName();
								
								//激活这个方法注值
								if("BigDecimal".equals(typeName)){// number
									try {
										//对带有指定参数的指定对象调用由此 Method 对象表示的底层方法
										method.invoke(t, rs.getInt(col));//整型
									} catch (Exception e) {
										method.invoke(t, rs.getDouble(col));//浮点型
									}
								}else {
									method.invoke(t, String.valueOf(obj));//字符串
								}
							}
							break;
						}
					}
				}
				list.add(t);
			}
		} catch (Exception e) {
			// TODO: handle exception
		}
		return list;
	}

2.getSetter()方法获取指定类的setter


/**
	 * 获取指定类的setter方法
	 * @param c
	 * @return
	 */
	public List<Method> getSetter(Class<?> c) {
		Method[] methods=c.getMethods();//获取类c中的所有方法
		List<Method> list=new ArrayList<Method>();
		for(Method method:methods){
			if(method.getName().startsWith("set")){//获取set方法
				list.add(method);
			}
		}
		return list;
	}

3.实例,用户信息类

package com.ylp.usersys.bean;

public class UserInfo {
	private int usid;
	private String uname;
	private int did;
	private String tel;
	private String photo;
	private String dname;
	
	public String getDname() {
		return dname;
	}
	public void setDname(String dname) {
		this.dname = dname;
	}
	public int getUsid() {
		return usid;
	}
	public void setUsid(int usid) {
		this.usid = usid;
	}
	public String getUname() {
		return uname;
	}
	public void setUname(String uname) {
		this.uname = uname;
	}
	public int getDid() {
		return did;
	}
	public void setDid(int did) {
		this.did = did;
	}
	public String getTel() {
		return tel;
	}
	public void setTel(String tel) {
		this.tel = tel;
	}
	public String getPhoto() {
		return photo;
	}
	//获取用户图片
	public String getPhotos() {
		if (photo==null||"".equals(photo)||"null".equals(photo)) {//如果没有图片,则显示指定图片
			return "<img src='images/zanwu.jpg' width='50px' height='50px'/>";
		}else if (photo.indexOf(",")>0) {//多张图片以“,”分隔
			String[] photos=photo.split(",");
			String str="";
			for(String p:photos){
				str+="<img src="+p+" width='50px' height='50px'/>";
			}
			return str;
		}else {//一张图片
			return "<img src="+photo+" width='50px' height='50px'/>";
		}
	}
	
	public void setPhoto(String photo) {
		this.photo = photo;
	}
	public UserInfo(int usid, String uname, int did, String tel, String photo,
			String dname) {
		super();
		this.usid = usid;
		this.uname = uname;
		this.did = did;
		this.tel = tel;
		this.photo = photo;
		this.dname = dname;
	}
	public UserInfo() {
		super();
	}
	@Override
	public int hashCode() {
		final int prime = 31;
		int result = 1;
		result = prime * result + did;
		result = prime * result + ((dname == null) ? 0 : dname.hashCode());
		result = prime * result + ((photo == null) ? 0 : photo.hashCode());
		result = prime * result + ((tel == null) ? 0 : tel.hashCode());
		result = prime * result + ((uname == null) ? 0 : uname.hashCode());
		result = prime * result + usid;
		return result;
	}
	@Override
	public boolean equals(Object obj) {
		if (this == obj)
			return true;
		if (obj == null)
			return false;
		if (getClass() != obj.getClass())
			return false;
		UserInfo other = (UserInfo) obj;
		if (did != other.did)
			return false;
		if (dname == null) {
			if (other.dname != null)
				return false;
		} else if (!dname.equals(other.dname))
			return false;
		if (photo == null) {
			if (other.photo != null)
				return false;
		} else if (!photo.equals(other.photo))
			return false;
		if (tel == null) {
			if (other.tel != null)
				return false;
		} else if (!tel.equals(other.tel))
			return false;
		if (uname == null) {
			if (other.uname != null)
				return false;
		} else if (!uname.equals(other.uname))
			return false;
		if (usid != other.usid)
			return false;
		return true;
	}
	@Override
	public String toString() {
		return "UserInfo [usid=" + usid + ", uname=" + uname + ", did=" + did
				+ ", tel=" + tel + ", photo=" + photo + ", dname=" + dname
				+ "]";
	}
	
	
}

4.UserDao

package com.ylp.usersys.dao;

import java.util.List;
import java.util.Map;

import com.ylp.usersys.bean.UserInfo;

public class UserDao {
	public List<UserInfo> find() {
		String sql="select usid,uname,tel,photo,u.did,dname from userInfo u,deptInfo d where u.did=d.did order by usid";
		DBHelper dbHelper=new DBHelper();
		return dbHelper.finds(sql, UserInfo.class);
	}
	
	public int  add(String uname,String did,String tel,String photo) {
		DBHelper dbHelper=new DBHelper();
		String sql="insert into userinfo values(seq_userinfo_usid.nextval,?,?,?,?)";
		return dbHelper.update(sql, uname,did,tel,photo);
	}
	
	/**
	 * 查询总记录数
	 * @return
	 */
	public int total() {
		DBHelper dbHelper=new DBHelper();
		String sql="select count(*) as total from userinfo";
		Map<String, String> map=dbHelper.findSingleByStr(sql);
		if (map!=null&&map.size()>0) {
			return Integer.parseInt(map.get("total"));
		}else {
			return 0;
		}
	}
	
	/**
	 * 分页查询
	 * @param pageNo 当前第几页
	 * @param pageSize 每页几条
	 * @return
	 */
	public List<UserInfo> find(Integer pageNo,Integer pageSize) {
		String sql="select * from (select a.*,rownum rn from (select u.*,dname from userInfo u left join  deptInfo d on u.did=d.did order by usid) a where rownum<=?) where rn>?";
		DBHelper dbHelper=new DBHelper();
		return dbHelper.finds(sql, UserInfo.class, pageNo*pageSize,(pageNo-1)*pageSize);
	}
	
	/**
	 * 分页按部门查询
	 * @param did 部门编号
	 * @return
	 */
	public List<UserInfo> findByDept(String did) {
		DBHelper dbHelper=new DBHelper();
		if ("-1".equals(did)) {
			String sql="select u.*,dname from userInfo u left join  deptInfo d on u.did=d.did  order by usid ";
			return dbHelper.finds(sql, UserInfo.class);
		}else if ("0".equals(did)) {
			String sql="select u.*,dname from userInfo u left join  deptInfo d on u.did=d.did  order by usid ";
			return dbHelper.finds(sql, UserInfo.class);
		}else {
			String sql="select u.*,dname from userInfo u left join  deptInfo d on u.did=d.did where  u.did=? order by usid ";
			return dbHelper.finds(sql, UserInfo.class, did);
		}
		
	}
}

5.使用获取到的UserInfo对象

UserDao userDao=new UserDao();
List<UserInfo> users=userDao.find();
for(UserInfo user:users){
    String uname=user.getUname();
    String usid=user.getUsid();
}


 


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值