java通用dao方法(优化多表联查)

本方法只介绍一个通用方法,本方法可应用在多表联查,可以不用多ji建javaBean也不需要把外键变成对象

1.准备一个pet实体类和DBlist工具类


package com.pet.entity;
 
import java.io.Serializable;
 
public class Pet implements Serializable {
 
	/**
	 * 
	 */
	private static final long serialVersionUID = 502943061295576054L;
	
	private Integer pet_id;
	private String pet_name;
	private Integer sort_id;
	private String pet_sex;
	private String pet_introduce;
	private Integer user_id;
	private Integer pet_informationPhoto_power;
	private Integer pet_informationPhoto_ability;
	private Integer pet_informationPhoto_height;
	private Integer pet_informationPhoto_integral;
	public Pet(Integer pet_id, String pet_name, Integer sort_id, String pet_sex, String pet_introduce, Integer user_id,
			Integer pet_informationPhoto_power, Integer pet_informationPhoto_ability,
			Integer pet_informationPhoto_height, Integer pet_informationPhoto_integral) {
		super();
		this.pet_id = pet_id;
		this.pet_name = pet_name;
		this.sort_id = sort_id;
		this.pet_sex = pet_sex;
		this.pet_introduce = pet_introduce;
		this.user_id = user_id;
		this.pet_informationPhoto_power = pet_informationPhoto_power;
		this.pet_informationPhoto_ability = pet_informationPhoto_ability;
		this.pet_informationPhoto_height = pet_informationPhoto_height;
		this.pet_informationPhoto_integral = pet_informationPhoto_integral;
	}
	public Pet(String pet_name, Integer sort_id, String pet_sex, String pet_introduce, Integer user_id,
			Integer pet_informationPhoto_power, Integer pet_informationPhoto_ability,
			Integer pet_informationPhoto_height, Integer pet_informationPhoto_integral) {
		super();
		this.pet_name = pet_name;
		this.sort_id = sort_id;
		this.pet_sex = pet_sex;
		this.pet_introduce = pet_introduce;
		this.user_id = user_id;
		this.pet_informationPhoto_power = pet_informationPhoto_power;
		this.pet_informationPhoto_ability = pet_informationPhoto_ability;
		this.pet_informationPhoto_height = pet_informationPhoto_height;
		this.pet_informationPhoto_integral = pet_informationPhoto_integral;
	}
	public Pet() {
		super();
	}
	public Integer getPet_id() {
		return pet_id;
	}
	public void setPet_id(Integer pet_id) {
		this.pet_id = pet_id;
	}
	public String getPet_name() {
		return pet_name;
	}
	public void setPet_name(String pet_name) {
		this.pet_name = pet_name;
	}
	public Integer getSort_id() {
		return sort_id;
	}
	public void setSort_id(Integer sort_id) {
		this.sort_id = sort_id;
	}
	public String getPet_sex() {
		return pet_sex;
	}
	public void setPet_sex(String pet_sex) {
		this.pet_sex = pet_sex;
	}
	public String getPet_introduce() {
		return pet_introduce;
	}
	public void setPet_introduce(String pet_introduce) {
		this.pet_introduce = pet_introduce;
	}
	public Integer getUser_id() {
		return user_id;
	}
	public void setUser_id(Integer user_id) {
		this.user_id = user_id;
	}
	public Integer getPet_informationPhoto_power() {
		return pet_informationPhoto_power;
	}
	public void setPet_informationPhoto_power(Integer pet_informationPhoto_power) {
		this.pet_informationPhoto_power = pet_informationPhoto_power;
	}
	public Integer getPet_informationPhoto_ability() {
		return pet_informationPhoto_ability;
	}
	public void setPet_informationPhoto_ability(Integer pet_informationPhoto_ability) {
		this.pet_informationPhoto_ability = pet_informationPhoto_ability;
	}
	public Integer getPet_informationPhoto_height() {
		return pet_informationPhoto_height;
	}
	public void setPet_informationPhoto_height(Integer pet_informationPhoto_height) {
		this.pet_informationPhoto_height = pet_informationPhoto_height;
	}
	public Integer getPet_informationPhoto_integral() {
		return pet_informationPhoto_integral;
	}
	public void setPet_informationPhoto_integral(Integer pet_informationPhoto_integral) {
		this.pet_informationPhoto_integral = pet_informationPhoto_integral;
	}
	@Override
	public String toString() {
		return "Pet [pet_id=" + pet_id + ", pet_name=" + pet_name + ", sort_id=" + sort_id + ", pet_sex=" + pet_sex
				+ ", pet_introduce=" + pet_introduce + ", user_id=" + user_id + ", pet_informationPhoto_power="
				+ pet_informationPhoto_power + ", pet_informationPhoto_ability=" + pet_informationPhoto_ability
				+ ", pet_informationPhoto_height=" + pet_informationPhoto_height + ", pet_informationPhoto_integral="
				+ pet_informationPhoto_integral + "]";
	}
	
	
 
}
package com.pet.util;
 
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
 
 
public class DBlist {
 
	
	
	public List<Map<String, Object>> convertList(ResultSet rs){
		
		//新建一个map list集合用于存放多条查询记录
		List<Map<String, Object>> li = new ArrayList();
		try {
			//结果集(rs)的结构信息,比如字段数和字段名等
			ResultSetMetaData rsmd = rs.getMetaData();
			// 取得查询出来的字段个数
			int columnCount = rsmd.getColumnCount();
			//迭代rs
			while(rs.next()) {
				//新建一个Map集合,将查询出内容按照字段名:值得键值对形式存储在map集合中
				Map<String, Object> rowDate = new HashMap<String,Object>();
				//循环所有查询出的字段
				for (int i = 1; i <=columnCount; i++) {
					rowDate.put(rsmd.getColumnName(i), rs.getObject(i));
					//获取第i个列名
					//getColumnName(i)
					//获取第i个对象的值
					//getObject(i)
				}
				//存放到list集合中
				li.add(rowDate);
			}
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
		}finally {
			
        try {
        	if (rs != null) {
                rs.close();
			}
		} catch (Exception e2) {
			// TODO: handle exception
			e2.printStackTrace();
		}
		}
 
 
		
		return li;
	}
	
	
}

2.写一个pageBean,这里面主要是分页操作

package com.pet.util;
 
import java.util.Map;
 
import javax.servlet.http.HttpServletRequest;
 
/**
 * 分页工具类
 * @author Administrator
 *2018年5月24日下午6:54:33
 */
public class PageBean {
	
	private int page=1;					//当前页
	private int rows=5;					//每页记录数
	private int total=0;				//总记录数
	
	private boolean pagination=true ;	//是否分页
	
	private String url; 				//根目录+请求地址
	
	private Map<String, String[]> map;	//请求参数
	
	public PageBean() {
		super();
		// TODO Auto-generated constructor stub
	}
	public PageBean(int page, boolean pagination) {
		super();
		this.page = page;
		this.pagination = pagination;
	}
	
	public PageBean(int page, int rows, int total, boolean pagination) {
		super();
		this.page = page;
		this.rows = rows;
		this.total = total;
		this.pagination = pagination;
	}
 
	public int getPage() {
		return page;
	}
 
	public void setPage(int page) {
		this.page = page;
	}
	
	//重载setPage
	public void setPage(String page) {
		if(page!=null&& !"".equals(page)) {
			this.page = Integer.parseInt(page);
		}	
	}
 
	public int getRows() {
		return rows;
	}
 
	public void setRows(int rows) {
		this.rows = rows;
	}
	
	//重载setRows
	public void setRows(String rows) {
		if(rows!=null&& !rows.equals("")) {
			this.rows = Integer.parseInt(rows);
		}
	}
 
	public int getTotal() {
		return total;
	}
 
	public void setTotal(int total) {
		this.total = total;
	}
	//重载setTotal
	public void setTotal(String total) {
		if(total!=null&& !total.equals("")) {
			this.total = Integer.parseInt(total);
		}		
	}
 
	public boolean isPagination() {
		return pagination;
	}
 
	public void setPagination(boolean pagination) {
		this.pagination = pagination;
	}
	
	//重载setPagination
	public void setPagination(String pagination) {
		if("false".equals(pagination) && pagination !=null) {
			this.pagination = false;
		}
	}
	
	public String getUrl() {
		return url;
	}
	public void setUrl(String url) {
		this.url = url;
	}
	public Map<String, String[]> getMap() {
		return map;
	}
	public void setMap(Map<String, String[]> map) {
		this.map = map;
	}
 
	
	
	@Override
	public String toString() {
		return "PageBean [page=" + page + ", rows=" + rows + ", total=" + total + ", pagination=" + pagination
				+ ", url=" + url + ", map=" + map + "]";
	}
	/**
	 * 计算起始记录的下标
	 * @return int
	 */
	public int getStartIndex() {
		return (this.page-1)*this.rows;
	}
	
	/**
	 * 计算总页数
	 * @return int
	 */
	public int getTotalPage() {
		int totalPage=this.total/this.rows;
		if(this.total%this.rows!=0) {
			totalPage++;
		}
		return totalPage;
	}
	
	/**
	 * 计算上一页
	 * @return int
	 */
	public int getPreviousPage() {
		int PreviousPage=this.page-1;
		if(PreviousPage<1) {
			PreviousPage=1;
		}
		return PreviousPage;
	}
	
	/**
	 * 计算下一页
	 * @return int
	 */ 
	public int getNextPage() {
		int NextPage=this.page+1;
		if(NextPage>this.getTotalPage()) {
			NextPage=this.getTotalPage();
		}
		return NextPage;
	}
	
	/**
	 * 初始化PageBean
	 * 实例化PageBean时,调用该方法重新为page,rows,pagination赋值和提交路径及参数(将上一次查询请求再发一次,只不过页码变了)
	 * @param request
	 */
	public void initPageBean(HttpServletRequest request) {
		//重新为page,rows,pagination赋值
		this.setPage(request.getParameter("page"));
		this.setRows(request.getParameter("rows"));
		this.setPagination(request.getParameter("pagination"));
		//提交路径及参数(将上一次查询请求再发一次,只不过页码变了)
		this.url=request.getContextPath()+request.getServletPath();
		this.map=request.getParameterMap();
	}
	
 
}

3.写一个Basedao类,CRUD的通用方法


package com.pet.dao;
 
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;
import java.util.Map;
 
import com.pet.util.DBHelper;
import com.pet.util.PageBean;
 
 
 
/**
 * CURD基础类
 * @author Administrator
 *2018年5月24日下午5:55:31
 */
public class BaseDao<E> {
 
 
/**
	 * 查询通用方法,支持模糊查询
	 * @param sql
	 * @param params
	 * @param callBack2
	 * @return List<Map<String, Object>>
	 */
	public List<Map<String, Object>> executeQuery3(String sql,PageBean pageBean,CallBack2<E> callBack){
		Connection con=null;
		PreparedStatement ps=null;
		ResultSet rs=null;
		try {
			con=DBHelper.getcon();
			//第一次查满足条件的总记录数
			if(pageBean!=null && pageBean.isPagination()) {
				//将普通的sql转换成查总记录数的getCountSql()
				String CountSql=this.getCountSql(sql);
				ps=con.prepareStatement(CountSql);
				rs=ps.executeQuery();
				if(rs.next()) {
					Object obj = rs.getObject(1);
					//取出结果集中的总记录数,赋给pageBean对象的总记录数属性
					pageBean.setTotal(obj.toString());
				}
				//关闭资源
				DBHelper.close(null, ps, rs);
			}
			//第二次查指定页码并满足条件的记录
			if (null != pageBean && pageBean.isPagination()) {
				//求总页数的方法getPageSql()
				sql = this.getPageSql(sql, pageBean);
			}
			ps=con.prepareStatement(sql);
			rs=ps.executeQuery();
			return callBack.forEach(rs);
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
		}finally {
			DBHelper.close(con, ps,rs);
		}
		
		return null;
	}
 
 
/**
	 * 将普通的sql转换成查总记录数的getCountSql()
	 * @param sql
	 * @return String
	 */
	private String getCountSql(String sql) {
		String CountSql="select count(*) from ("+sql+") a";
		return CountSql;
	}
	
	/**
	 * 求总页数的方法getPageSql()
	 * @param sql
	 * @param pageBean
	 * @return String
	 */
	private String getPageSql(String sql,PageBean pageBean) {
		String PageSql=sql+" limit "+pageBean.getStartIndex()+","+pageBean.getRows();
		return PageSql;
	}
}

然后就是使用了,我们先继承Basedao类

public class PetDaoImpl extends BaseDao<Pet> implements IPetDao {
 
@SuppressWarnings({ "unchecked", "rawtypes" })
	public List<Map<String, Object>> getPetById2(Pet p,PageBean pageBean) {
		// TODO Auto-generated method stub
		String sql = "select a.*,b.user_name,b.user_pwd,b.user_email from t_pet a,t_user b where a.user_id=b.user_id";
		return new BaseDao().executeQuery3(sql, pageBean, new BaseDao.CallBack2<Object>() {
 
			public List<Map<String, Object>> forEach(ResultSet rs) throws SQLException {
				// TODO Auto-generated method stub
				List<Map<String, Object>> li = null;
				DBlist db = new DBlist();
				li = db.convertList(rs);
				return li;
			}
		});
	}
}

 测试

public class Dao {
 
	@Test
	public void test() {
		IPetDao ipd = new PetDaoImpl();
		Pet p = new Pet();
		PageBean pageBean = new PageBean();
		List<Map<String, Object>> petById2 = ipd.getPetById2(p,pageBean);
		System.out.println(petById2);
	}
}

 注意:因为使用的是Map集合,所以你数据库查询的字段名不能有重复的的,所以多表联查时要把字段名给打出来

原文地址:https://blog.csdn.net/qq_40132161/article/details/81383783

猜你喜欢

转载自blog.csdn.net/LYQ2332826438/article/details/81386212
今日推荐