1. 程式人生 > >Java 常用工具類

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();
		}
	
	  
	  
}