是用orm映射封装自己封装dao层
思路:通过映射获得实体类的属性拼接sql语句
import java.lang.reflect.Field; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.util.ArrayList; import java.util.List; import java.util.Map; import club.itstu.MyUtil.DbUtil; import club.itstu.MyUtil.StringUtil; /** * orm基础封装类 * BaseDao.java * @author Mr储 * 2016-10-20 下午9:59:30 */ public class BaseDao<T> { private Class cls = null; //所操作是同类对应的Calss private String tableName = null; //数据库的表名 private T t = (T) this; //当前对象 public DbUtil db = DbUtil.getInstance();//获取数据库的连接 public BaseDao(String tableName,Class cls){ super(); this.tableName = tableName; this.cls = cls; } /** * 保存对象(向数据库中增加数据) */ public boolean save(){ //通过映射获取实体类中的属性 Field[] fields = cls.getDeclaredFields();//获取类所有属性 //将要拼接的sql拆开 StringBuffer sqlbf1 = new StringBuffer("insert into "+tableName+" (");//存列名 StringBuilder sqlbf2 = new StringBuilder(" values ("); for(Field f:fields){ f.setAccessible(true);//私有属性设为可读 sqlbf1.append(f.getName()+","); try { if(f.get(t)==null||StringUtil.isEmpty(f.get(t)+"")){ sqlbf2.append("null,"); }else{ sqlbf2.append("'"+f.get(t)+"',"); } } catch (IllegalArgumentException e) { e.printStackTrace(); return false; } catch (IllegalAccessException e) { e.printStackTrace(); return false; } } String sql1 = sqlbf1.substring(0,sqlbf1.length()-1)+")"; String sql2 = sqlbf2.substring(0,sqlbf2.length()-1)+")"; db.insert(sql1+sql2);//执行sql return true; } /** * 查询单个对象(一条记录) * */ public T find(){ //通过映射获得所有属性 Field[] fields = cls.getDeclaredFields(); //1=1 方便sql的拼接 StringBuffer sqlsb = new StringBuffer("select * from "+tableName+" where 1=1"); List<Object> params = new ArrayList<Object>();//存取属的值 List<String> fieldNmaeList = new ArrayList<String>();//存取属性名 //判读所有属性值是否为空 boolean paramsFlag = true; for(Field f : fields){ f.setAccessible(true);//将属性设为可读的 fieldNmaeList.add(f.getName());//将属性名全部添加到容器中 try { //判断该属性的值是否为空 +""将任何类型转换为字符串 if(f.get(t)!=null&&StringUtil.isNotEmpty(f.get(t)+"")){ sqlsb.append(" and "+f.getName()+"=? ");//在sql上添加查询条件 params.add(f.get(t));//将该值添加到容器中 paramsFlag = false;//将属性值改为不全部为空 } } catch (IllegalArgumentException e) { e.printStackTrace(); } catch (IllegalAccessException e) { e.printStackTrace(); } } if(paramsFlag){//属性值权为空 返回空的对象 return t; }else{ //部位空时从数据库中取出满足改条件的记录 List<Map<String,Object>> rstList = db.query(sqlsb.toString(),params); if(!rstList.isEmpty()){ Map<String,Object> m = rstList.get(0);//取出该条数据 //遍历将该数据 并通过属性名将该记录刚给属性赋值 for(String fieldName : fieldNmaeList){ Object value = m.get(fieldName); //通过映射给对象赋值 setValue(fieldName,value); } } } //返回该对象 return t; } /** * 查询多个对象 */ public List<T> findAll(){ List<T> resTList = new ArrayList<T>();//用来存储多个结果集 Field[] fields = cls.getDeclaredFields();//获取类所有属性 StringBuffer sfSql = new StringBuffer("select * from "+tableName+" where 1=1"); List<Object> params = new ArrayList<Object>();//存属性值 List<String> fieldNameList = new ArrayList<String>();//存属性名 for(Field f:fields){ f.setAccessible(true);//私有属性设为可读 fieldNameList.add(f.getName()); try { if(f.get(t)!=null){ sfSql.append(" and " +f.getName()+"=? "); params.add(f.get(t)); } } catch (IllegalArgumentException e) { e.printStackTrace(); } catch (IllegalAccessException e) { e.printStackTrace(); } } List<Map<String,Object>> resList = db.query(sfSql.toString(), params); try { if(!resList.isEmpty()){ //遍历多个结果集存入T类型的对象中 for(Map<String,Object> map:resList){ T tt = (T) cls.newInstance(); for(String fieldName:fieldNameList){ Object value = map.get(fieldName); setValue(fieldName,value,tt); } resTList.add(tt); } } } catch (InstantiationException e) { e.printStackTrace(); } catch (IllegalAccessException e) { e.printStackTrace(); } return resTList; } /** * 实体对象属性赋值 * @param name 属性名 * @param value 属性值 */ private void setValue(String name,Object value){ String setName = name.substring(0,1).toUpperCase()+name.substring(1);//将属性名的首字母大写 String type = null; if(value!=null){ type = value.getClass().getName(); if(type.equalsIgnoreCase("java.sql.Timestamp")||type.equalsIgnoreCase("java.sql.Date")){ // type = "java.util.Date"; type= "java.lang.String"; value = value+""; } } try { if(value!=null){ Method method = cls.getDeclaredMethod("set"+setName, Class.forName(type)); method.invoke(t, value); } } catch (NoSuchMethodException e) { e.printStackTrace(); } catch (SecurityException e) { e.printStackTrace(); } catch (ClassNotFoundException e) { e.printStackTrace(); }catch (Exception e) { e.printStackTrace(); } } /** * 实体对象属性赋值 * @param name 属性名 * @param value 属性值 * @param obj 要赋值的对象 */ private void setValue(String name,Object value,T obj){ String setName = name.substring(0,1).toUpperCase()+name.substring(1);//将属性名的首字母大写 String type = null; if(value!=null){ type = value.getClass().getName(); if(type.equalsIgnoreCase("java.sql.Timestamp")||type.equalsIgnoreCase("java.sql.Date")){ //type = "java.util.Date"; value = value+""; type = "java.lang.String"; } } try { if(type!=null){ Method method = cls.getDeclaredMethod("set"+setName, Class.forName(type)); method.invoke(obj, value); } } catch (SecurityException e) { e.printStackTrace(); } catch (ClassNotFoundException e) { e.printStackTrace(); }catch (Exception e) { e.printStackTrace(); } } /** * 根据id 删除对象 */ public boolean deleteById(){ Method method =null; Integer id = null; try { method = cls.getDeclaredMethod("getId"); id = (Integer)method.invoke(t); if(id==null){ throw new Exception("主键为空"); }else{ db.delete("delete from "+tableName+" where id=?",id); } } catch (NoSuchMethodException e) { e.printStackTrace(); } catch (SecurityException e) { e.printStackTrace(); } catch (IllegalAccessException e) { e.printStackTrace(); } catch (IllegalArgumentException e) { e.printStackTrace(); } catch (InvocationTargetException e) { e.printStackTrace(); } catch (Exception e) { e.printStackTrace(); } return true; } /** * 根据id更新 */ public boolean updateById(){ //获取所有属性 Field[] fields = cls.getDeclaredFields(); //sql语句 StringBuffer sqlsb = new StringBuffer("update "+tableName+" set "); Integer id = null; for(Field f : fields){ f.setAccessible(true);//将属性设为可读的 try { //是“id”这个属性进入判断 if("id".equalsIgnoreCase(f.getName())){ //获得的对象为空更新失败 if(f.get(t)==null){ throw new Exception("主键id为空跟新失败"); }else{ //将该值赋给id id = (Integer)f.get(t); } }else if(f.get(t)!=null){//对象不为空进入拼接sql语句 sqlsb.append(f.getName()+"='"+f.get(t)+"',"); } } catch (IllegalArgumentException e) { e.printStackTrace(); return false; } catch (IllegalAccessException e) { e.printStackTrace(); return false; } catch (Exception e) { e.printStackTrace(); return false; } } String sql = sqlsb.toString(); if(sql.endsWith(",")){//该字符串逗号结束 说明属性有值 去除逗号 拼接sql sql = sql.substring(0,sql.length()-1)+" where id="+id; }else{ try { throw new Exception("属性值为空,跟新失败"); } catch (Exception e) { e.printStackTrace(); return false; } } db.update(sql);//执行 return true; } }