欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

基于JDBC封装的BaseDao(实例代码)

程序员文章站 2024-03-12 23:34:21
最近闲暇时萌发写一写dao的封装的例子,就将以前写的整理一下。 public class basedao { connection co...

最近闲暇时萌发写一写dao的封装的例子,就将以前写的整理一下。

public class basedao<t> {

	connection conn;
	preparedstatement st;
	resultset rs;
	
	jdbcutil jdbcutil = new jdbcutil();
	
	int result = 0;
	
	private class<t> persistentclass;
	
	@suppresswarnings("unchecked")
	public basedaoutil(){		
		conn = jdbcutil.getconnection();
		parameterizedtype type = (parameterizedtype) getclass().getgenericsuperclass();
		persistentclass = (class<t>) type.getactualtypearguments()[0];		
	}
	
	
  /**
   * 保存
    * @param entity
   * @return
   */
	public int save(t entity) throws exception{
		
		string sql = "insert into "+ entity.getclass().getsimplename().tolowercase() +" (";
		
		list<method> list = this.matchpojomethods(entity,"get");
		
		iterator<method> iter = list.iterator();
			
		object obj[] = new object[list.size()];
		int i = 0;
		//拼接字段顺序 insert into table name(id,name,email,
         while(iter.hasnext()) {
            method method = iter.next();
            sql += method.getname().substring(3).tolowercase() + ","; 
            if (method.getreturntype().getsimplename().indexof("date") !=-1) {
				simpledateformat sbf = new simpledateformat("yyyy-mm-dd hh:mm:ss");
				obj[i] = sbf.format(method.invoke(entity, new object[]{}));
		   }else {
				obj[i] = method.invoke(entity, new object[]{});
		   }     
      i++;
    }
    
    //去掉最后一个,符号insert insert into table name(id,name,email) values(
    sql = sql.substring(0, sql.lastindexof(",")) + ") values(";
    
    //拼装预编译sql语句insert insert into table name(id,name,email) values(?,?,?,
    for(int j = 0; j < list.size(); j++) {
    	sql += "?,"; 
    }

    //去掉sql语句最后一个,符号insert insert into table name(id,name,email) values(?,?,?);
    sql = sql.substring(0, sql.lastindexof(",")) + ")";
    
    //到此sql语句拼接完成,打印sql语句
    system.out.println(sql);
    
    try {
    	st = conn.preparestatement(sql);
    	for (int j = 0; j < obj.length; j++) {
				st.setobject(j+1, obj[j]);
			}
			result = st.executeupdate();
		} catch (sqlexception e) {
			e.printstacktrace();
		}
    
		jdbcutil.getclose(rs, st, conn);
		
		return result;	
	}
	
	/**
	 * 删除
	 * @param object
	 * @return
	 * @throws sqlexception
	 */
	public int deleteid(object object) throws exception{
		
		string sql = "delete from "+ persistentclass.getsimplename().tolowercase() +" where ";
		
		//通过子类的构造函数,获得参数化类型的具体类型.比如basedao<t>也就是获得t的具体类型
    t entity = persistentclass.newinstance();
    
    //存放pojo(或被操作表)主键的方法对象
    method idmethod = null;
    
    list<method> list = this.matchpojomethods(entity, "set");
    iterator<method> iter = list.iterator();
    
    //过滤取得method对象
    while(iter.hasnext()) {
      method tempmethod = iter.next();
      if(tempmethod.getname().indexof("id") != -1 && tempmethod.getname().substring(3).length() == 2) {
        idmethod = tempmethod;
      } else if((entity.getclass().getsimplename() + "id").equalsignorecase(tempmethod.getname().substring(3))){
        idmethod = tempmethod;
      }
    }
    //第一个字母转为小写
    sql += idmethod.getname().substring(3,4).tolowercase()+idmethod.getname().substring(4) + " = ?";
    	
		system.out.println(sql);
		
		st = conn.preparestatement(sql);
		
		//判断id的类型
    if(object instanceof integer) {
      st.setint(1, (integer)object);
    } else if(object instanceof string){
      st.setstring(1, (string)object);
    }
		
		result = st.executeupdate();
		
		jdbcutil.getclose(rs, st, conn);
		
		return result;	
	}
	
	/**
	 * 修改
	 * @param entity
	 * @return
	 * @throws exception
	 */
	public int update(t entity) throws exception{
		
		string sql = "update "+ entity.getclass().getsimplename().tolowercase() +" set ";
		
		list<method> list = this.matchpojomethods(entity, "get");
		
		//装载参数
		object obj[] = new object[list.size()];
		int i = 0;
		
		//临时method对象,负责迭代时装method对象.
    method tempmethod = null;
    
    //由于修改时不需要修改id,所以按顺序加参数则应该把id移到最后.
    method idmethod = null;
    iterator<method> iter = list.iterator();
    while(iter.hasnext()) {
      tempmethod = iter.next();
 
      //如果方法名中带有id字符串并且长度为2,则视为id.
      if(tempmethod.getname().lastindexof("id") != -1 && tempmethod.getname().substring(3).length() == 2) {
      	obj[list.size()-1] = tempmethod.invoke(entity, new object[]{});
        //把id字段的对象存放到一个变量中,然后在集合中删掉.
        idmethod = tempmethod;
        iter.remove();
      //如果方法名去掉set/get字符串以后与pojo + "id"想符合(大小写不敏感),则视为id
      } else if((entity.getclass().getsimplename() + "id").equalsignorecase(tempmethod.getname().substring(3))) {
      	obj[list.size()-1] = tempmethod.invoke(entity, new object[]{});
      	idmethod = tempmethod;
        iter.remove();        
      }
    }
		
    //把迭代指针移到第一位
    iter = list.iterator();
    while(iter.hasnext()) {
      tempmethod = iter.next();
      sql += tempmethod.getname().substring(3).tolowercase() + "= ?,";
      obj[i] = tempmethod.invoke(entity, new object[]{});
      i++;
    }
    
    //去掉最后一个,符号
    sql = sql.substring(0,sql.lastindexof(","));
    
    //添加条件
    sql += " where " + idmethod.getname().substring(3).tolowercase() + " = ?";
    
    //sql拼接完成,打印sql语句
    system.out.println(sql);
		
    st = conn.preparestatement(sql);
    
    for (int j = 0; j < obj.length; j++) {
			st.setobject(j+1, obj[j]);
		}
    
    result = st.executeupdate();

    jdbcutil.getclose(rs, st, conn);
    
		return result;

	}
	
	
	public t findbyid(object object) throws exception{
		
		string sql = "select * from "+ persistentclass.getsimplename().tolowercase() +" where ";
		
		//通过子类的构造函数,获得参数化类型的具体类型.比如basedao<t>也就是获得t的具体类型
    t entity = persistentclass.newinstance();
    
    //存放pojo(或被操作表)主键的方法对象
    method idmethod = null;
    
    list<method> list = this.matchpojomethods(entity, "set");
    iterator<method> iter = list.iterator();
    
    //过滤取得method对象
    while(iter.hasnext()) {
      method tempmethod = iter.next();
      if(tempmethod.getname().indexof("id") != -1 && tempmethod.getname().substring(3).length() == 2) {
        idmethod = tempmethod;
      } else if((entity.getclass().getsimplename() + "id").equalsignorecase(tempmethod.getname().substring(3))){
        idmethod = tempmethod;
      }
    }
    //第一个字母转为小写
    sql += idmethod.getname().substring(3,4).tolowercase()+idmethod.getname().substring(4) + " = ?";
    	
		system.out.println(sql);
		
		st = conn.preparestatement(sql);
		
		//判断id的类型
    if(object instanceof integer) {
      st.setint(1, (integer)object);
    } else if(object instanceof string){
      st.setstring(1, (string)object);
    }
		
    rs = st.executequery();
        
    //把指针指向迭代器第一行
    iter = list.iterator();
    
    //封装
    while(rs.next()) {
      while(iter.hasnext()) {
        method method = iter.next();
        if(method.getparametertypes()[0].getsimplename().indexof("string") != -1) {
          //由于list集合中,method对象取出的方法顺序与数据库字段顺序不一致(比如:list的第一个方法是setdate,而数据库按顺序取的是"123"值)
          //所以数据库字段采用名字对应的方式取.
          this.setstring(method, entity, rs.getstring(method.getname().substring(3).tolowercase()));
        } else if(method.getparametertypes()[0].getsimplename().indexof("date") != -1){
          this.setdate(method, entity, rs.getdate(method.getname().substring(3).tolowercase()));
        }else {
          this.setint(method, entity, rs.getint(method.getname().substring(3).tolowercase()));
        }  
      }
    }
		
    jdbcutil.getclose(rs, st, conn);
    
		return entity;
		
	}
	
	
	
	
	
	/**
   * 过滤当前pojo类所有带传入字符串的method对象,返回list集合.
   */
  private list<method> matchpojomethods(t entity,string methodname) {
    //获得当前pojo所有方法对象
    method[] methods = entity.getclass().getdeclaredmethods();
    
    //list容器存放所有带get字符串的method对象
    list<method> list = new arraylist<method>();
    
    //过滤当前pojo类所有带get字符串的method对象,存入list容器
    for(int index = 0; index < methods.length; index++) {
      if(methods[index].getname().indexof(methodname) != -1) {
        list.add(methods[index]);
      }
    }    
    return list;
  }
  

  /**
   * 参数类型为string时,为entity字段设置参数,对应set
   */
  public string setstring(method method, t entity, string arg) throws exception{
    return (string)method.invoke(entity, new object[]{arg});
  }
  
  
  /**
   * 参数类型为date时,为entity字段设置参数,对应set
   */
  public date setdate(method method, t entity, date arg) throws exception{
    return (date)method.invoke(entity, new object[]{arg});
  }
	
	
  /**
   * 参数类型为integer或int时,为entity字段设置参数,对应set
   */
  public integer setint(method method, t entity, integer arg) throws exception{
    return (integer)method.invoke(entity, new object[]{arg});
  }
 	
}

以上这篇基于jdbc封装的basedao(实例代码)就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持。