Java 常用工具类

  1. PageBaen 分页工具类
package com.strurts.utli;

import java.util.Map;

import javax.servlet.http.HttpServletRequest;

public class PageBean {

	private int page = 1;// 页码
	private int rows = 2;// 行数/页大小
	private int total = 0;// 总记录数

	private boolean pagination = true;// 默认分页

	private String url;// 上一次请求的地址
	private Map<String, String[]> parameterMap;// 上一次请求的所有参数

	public PageBean() {
		super();
	}

	/**
	 * 对分页bean进行初始化
	 * 
	 * @param request
	 */
	public void setRequest(HttpServletRequest request) {
		// 公共参数
		this.setPage(request.getParameter("page"));
		this.setRows(request.getParameter("rows"));
		this.setPagination(request.getParameter("pagination"));

		// 请求地址和请求参数
		this.setUrl(request.getContextPath() + request.getServletPath());
		this.setParameterMap(request.getParameterMap());
	}

	public String getUrl() {
		return url;
	}

	public void setUrl(String url) {
		this.url = url;
	}

	public Map<String, String[]> getParameterMap() {
		return parameterMap;
	}

	public void setParameterMap(Map<String, String[]> parameterMap) {
		this.parameterMap = parameterMap;
	}

	public int getPage() {
		return page;
	}

	public void setPage(int page) {
		this.page = page;
	}

	public void setPage(String page) {
		if (null != page && !"".equals(page.trim())) {
			this.page = Integer.parseInt(page);
		}
	}

	public int getRows() {
		return rows;
	}

	public void setRows(int rows) {
		this.rows = rows;
	}

	public void setRows(String rows) {
		if (null != rows && !"".equals(rows.trim())) {
			this.rows = Integer.parseInt(rows);
		}
	}

	public int getTotal() {
		return total;
	}

	public void setTotal(int total) {
		this.total = total;
	}

	public void setTotal(String total) {
		this.total = Integer.parseInt(total);
	}

	public boolean isPagination() {
		return pagination;
	}

	public void setPagination(boolean pagination) {
		this.pagination = pagination;
	}

	public void setPagination(String pagination) {
		if ("false".equals(pagination)) {
			this.pagination = false;
		}
	}

	/**
	 * 下一页
	 * 
	 * @return
	 */
	public int getNextPage() {
		int nextPage = page + 1;
		if (nextPage > this.getMaxPage()) {
			nextPage = this.getMaxPage();
		}
		return nextPage;
	}

	/**
	 * 上一页
	 * 
	 * @return
	 */
	public int getPreviousPage() {
		int previousPage = page - 1;
		if (previousPage < 1) {
			previousPage = 1;
		}
		return previousPage;
	}

	/**
	 * 最大页码
	 * 
	 * @return
	 */
	public int getMaxPage() {
		return total % rows == 0 ? total / rows : total / rows + 1;
	}

	/**
	 * 起始记录的下标
	 * 
	 * @return
	 */
	public int getStartIndex() {
		return (page - 1) * rows;
	}

	@Override
	public String toString() {
		return "PageBean [page=" + page + ", rows=" + rows + ", total=" + total + ", pagination=" + pagination + "]";
	}

}

  1. StringUtils 判断字符串是否为空的类
package com.hibernateSql.util;


public class StringUtils {
	// 私有的构造方法,保护此类不能在外部实例化
	private StringUtils() {
	}

	/**
	 * 如果字符串等于null或去空格后等于"",则返回true,否则返回false
	 * 
	 * @param s
	 * @return
	 */
	public static boolean isBlank(String s) {
		boolean b = false;
		if (null == s || s.trim().equals("")) {
			b = true;
		}
		return b;
	}
	
	/**
	 * 如果字符串不等于null或去空格后不等于"",则返回true,否则返回false
	 * 
	 * @param s
	 * @return
	 */
	public static boolean isNotBlank(String s) {
		return !isBlank(s);
	}

}

  1. Hibernate 查询通用BaseDao
package com.hibernateSql.dao;
import java.util.Collection;
import java.util.List;
import java.util.Map;

import org.hibernate.Session;
import org.hibernate.query.Query;

import com.hibernateSql.util.PageBean;

/**
 * jdbc:
 * executeQuery(pagebean,sql,clz)
 * sql: select * from book where book_name '%?%'
 *      select * from book where book_name '%xx%'
 * 
 * 分页:1.sql-->countSql-->total-->pagebaen
 *      2.sql-->pagesql-->result
 *      3.处理结果集
 * 
 * hibername
 * 分页:
 * 1.hql-->countHql-->total-->pagebaen
 * 2.Hql-->pageHql-->result
 * 
 * @author Administrator
 *
 */
public class BaseDao {
	
	/**
	 * 如果有带参数,
	 * 命名参数 :赋值
	 * 
	 * @param query
	 * @param hql
	 */
	public void setParameters(Query<?> query,Map<String, Object> map) {
		
		if(map == null || map.size()==0) {
			return ;
		}
		else {
			//创建map的视图
			Object values=null;
		   for (Map.Entry<String, Object> entry : map.entrySet()) {
			   
			   values=entry.getValue();
			   //判断它的数据类型
			   if(values instanceof Collection) {
				   query.setParameterList(entry.getKey(), (Collection) values);
			   }
			   else if(values instanceof Object[]) {
				   query.setParameterList(entry.getKey(), (Object[]) values);
			   }
			   else {
				   query.setParameter(entry.getKey(), values);
					 
			   }
			   
		}	
			
		}
		
	} 
	
	

	
	/**
	 * 拼接Hqlcount语句
	 */
	
	public String getcountHql(String hql) {
		int index = hql.toUpperCase().indexOf("FROM");
		
		return "select count(*) "+ hql.substring(index);
		
	}
	
	
	
	
	/**
	 * 
	 */
	public List<?> executeQuery(String hql,Map<String, Object> map,PageBean pageBean,Session session){
		
		//判断它是否分页
		if(pageBean != null && pageBean.isPagination()) {
			 //如果分页
			String countHql = getcountHql(hql);
			 //查询出总页数
			Query<?>  query = session.createQuery(countHql); 
			//给这个countHql中的命名参数赋值
			setParameters(query, map);
			String total = query.getSingleResult().toString();
			
			//放入pageBeau
			pageBean.setTotal(total);
			
			
			
			//开始查询数据
			Query<?>  pageQuery = session.createQuery(hql);
			//给命名参数赋值
			this.setParameters(pageQuery, map);
			//设置分页
			pageQuery.setFirstResult(pageBean.getStartIndex());
			pageQuery.setMaxResults(pageBean.getRows());
			
			
			return pageQuery.list();
		}
		else {
			
			//不分页的时候
			Query<?> query = session.createQuery(hql);
			
			//给参数赋值
			setParameters(query, map);
			
			
			return query.list();
		}
		
		
		

	}
	

}

  1. 获取Map , 根据传递过来到key获取里面到值
package com.strurts.utli;

import java.util.Arrays;
import java.util.Map;

public class JsonUtil {

	/**
	 *    获取Map , 根据传递过来到key获取里面到值
	 * @param map
	 * @param key
	 * @return
	 */
	public static String getParamMapVal(Map<String, String[]> map,String key) {
		if(map!=null&&map.size()>0) {
			String[] vals = map.get(key);
			if(vals!=null&&vals.length>0) {
				 String val = Arrays.toString(vals);
				 
				 return val.substring(1, val.length()-1);
			}
		}
		
		return "";
		
		
	}
}

  1. BaseDao 利用oop思想进行增强的一个通用查询分页类
package com.zking.util;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;

/**
 * 利用oop思想进行增强的一个通用查询分页类
 * @author Administrator
 *
 * @param <T>
 */
public class BaseDao<T> {
	/**
	 * 沿用的思想类似于ajax
	 * success:function{
	 * }
	 * @author Administrator
	 *
	 */
	public abstract class CallBack{
		public abstract List<T> forEach(ResultSet rst,Connection con) throws SQLException, InstantiationException, IllegalAccessException;
	}
	
	/**
	 * 
	 * @param sql
	 * @param pageBean
	 * @param callBack
	 * @return
	 * @throws SQLException
	 * @throws InstantiationException
	 * @throws IllegalAccessException
	 */
	public List<T> executeQuery(String sql, PageBean pageBean,CallBack callBack) throws SQLException, InstantiationException, IllegalAccessException {
		Connection con = DBAccess.getConnection();
		if(pageBean.isPagination()) {
			String countSql = getCountSql(sql);
			PreparedStatement pst = con.prepareStatement(countSql);
			ResultSet rst = pst.executeQuery();
			if(rst.next()) {
				pageBean.setTotal(rst.getObject(1).toString());
			}
		}
		
		String pageSql = getPageSql(sql,pageBean);
		PreparedStatement pst = con.prepareStatement(pageSql);
		ResultSet rst = pst.executeQuery();
		return callBack.forEach(rst, con);
	}

	/**
	 * 拼装分页的sql语句
	 * @param sql
	 * @param PageBean
	 * @return
	 */
	private String getPageSql(String sql, PageBean pageBean) {
		int page = pageBean.getPage();
		int rows = pageBean.getRows();
		int startIndex = (page - 1) * rows;
		return pageBean.isPagination() ? (sql + " limit "+ startIndex +"," + rows) : sql;
	}

	/**
	 * 获取符合记录数的sql语句
	 * @param sql
	 * @return
	 */
	private String getCountSql(String sql) {
		return "select count(*) from ("+ sql +") t;";
	}
}

  1. EntityBaseDao 利用反射对通用分页查询进行二次增强
package com.zking.util;

import java.lang.reflect.Field;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

/**
 * 利用反射对通用分页查询进行二次增强
 * @author Administrator
 *
 * @param <T>
 */
public class EntityBaseDao<T> extends BaseDao<T> {
	public List<T> executeQuery(String sql, PageBean pageBean, Class<T> clz) throws SQLException, InstantiationException, IllegalAccessException{
		return super.executeQuery(sql, pageBean, new CallBack() {

			@Override
			public List<T> forEach(ResultSet rst,Connection con) throws SQLException, InstantiationException, IllegalAccessException {
				List<T> list = new ArrayList<>();
				while(rst.next()) {
//					1、实例化一个具体的类对象出来
//					2、给具体的哪一个类对象赋值(用于页面展示)
//					3、要通过类对象的属性从ResultSet拿到数据
//					4、把装有数据的实体类添加给list
//					list.add(new Book(rst.getInt("bid"), rst.getString("bname"), rst.getFloat("price")));
					T t = (T) clz.newInstance();
					Field[] declaredFields = clz.getDeclaredFields();
					for (Field field : declaredFields) {
						field.setAccessible(true);
						field.set(t, rst.getObject(field.getName()));
					}
					list.add(t);
				}
				return list;
			}
		});
	}
	
	/**
	 * 通用的增删改方法
	 * @param sql	增删改的sql语句
	 * @param attrs	要个sql语句的那个表字段进行赋值,需要调用方传递过来
	 * @param t		具体要给哪个对象进行增删改操作
	 * @return
	 * @throws SQLException
	 * @throws InstantiationException
	 * @throws IllegalAccessException
	 * @throws SecurityException 
	 * @throws NoSuchFieldException 
	 */
	public int executeUpdate(String sql, String[] attrs, T t) throws SQLException, InstantiationException, IllegalAccessException, NoSuchFieldException, SecurityException{
		Connection con = DBAccess.getConnection();
		PreparedStatement pst = con.prepareStatement(sql);
//		给sql语句预定义对象赋值
		for (int i = 0; i < attrs.length; i++) {
			Field attrField = t.getClass().getDeclaredField(attrs[i]);
			attrField.setAccessible(true);
			int j = i+1;
			pst.setObject(j, attrField.get(t));
		}
		return pst.executeUpdate();
	}
}

  1. JsonBaseDao json格式的通用查询
package com.zking.util;

import java.lang.reflect.Field;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * json格式的通用查询
 * @author Administrator
 *
 */
public class JsonBaseDao extends BaseDao<Map<String, Object>>{

	  public List<Map<String, Object>> executeQuery(String sql, PageBean pageBean)
			throws SQLException, InstantiationException, IllegalAccessException {
	
		return super.executeQuery(sql, pageBean, new CallBack() {
			
			@Override
			public List<Map<String, Object>> forEach(ResultSet rst,Connection con)
					throws SQLException, InstantiationException, IllegalAccessException {
				List<Map<String, Object>> list=new  ArrayList<>();
				ResultSetMetaData md=rst.getMetaData();
				int columnCount = md.getColumnCount();
				Map<String, Object> map=null;
				while(rst.next()) {
					map=new HashMap<>();
					for (int i = 1; i <=columnCount; i++) {
						map.put(md.getColumnName(i), rst.getObject(i));
				     
					}
					list.add(map);
				}
				con.close();
				return list;
			}
		});
	}
	  
	  
	  /**
	   * 通用增删改
	   */
		public int executeUpdate(String sql, String[] keys,Map<String, String[]> map) throws SQLException, InstantiationException, IllegalAccessException, NoSuchFieldException, SecurityException{
			Connection con = DBAccess.getConnection();
			PreparedStatement pst = con.prepareStatement(sql);
//			给sql语句预定义对象赋值
			for (int i = 0; i < keys.length; i++) {
			   pst.setObject(i+1, JsonUtil.getParamMapVal(map,keys[i]));
			}
			return pst.executeUpdate();
		}
	
	  
	  
}

猜你喜欢

转载自blog.csdn.net/zimuliusu/article/details/83547462