当前位置: 移动技术网 > IT编程>开发语言>Java > 简单通用JDBC辅助类封装(实例)

简单通用JDBC辅助类封装(实例)

2019年07月22日  | 移动技术网IT编程  | 我要评论

哎,最近很好久没写点东西了,由于工作的原因,接触公司自己研发的底层orm框架,偶然发现该框架在调用jdbc操作的时候参考的是hibernate 里面的simplejdbctemplate,这里我想到了在大学的时候自己用过的一个简单的jdbc封装,现在我将代码贴出来,和大家一起分享:

config类:读取同一包下的数据库连接配置文件,这样是为了更好的通用性考虑

package com.tly.dbutil;

import java.io.ioexception;
import java.util.properties;

public class config {
  private static properties prop = new properties();  
  static{    
    try {
      //加载dbconfig.properties配置文件
      prop.load(config.class.getresourceasstream("dbconfig.properties"));
    } catch (ioexception e) {
      // todo auto-generated catch block
      e.printstacktrace();
    }
  }
  
  //设置常量
  public static final string class_name = prop.getproperty("class_name");
  public static final string database_url = prop.getproperty("database_url");
  public static final string server_ip = prop.getproperty("server_ip");
  public static final string server_port = prop.getproperty("server_port");
  public static final string database_sid = prop.getproperty("database_sid");
  public static final string username = prop.getproperty("username");
  public static final string password = prop.getproperty("password");
  
}

dbconfig.properties:数据库配置文件,你也可以用xml格式等,注意config类里面该文件的调用位置

class_name=com.mysql.jdbc.driver
database_url=jdbc:mysql
server_ip=localhost
server_port=3306
database_sid=employees
username=root
password=1

接下来就是数据库连接辅助类dbconn了

package com.employees.dbutil;

import java.sql.connection;
import java.sql.drivermanager;
import java.sql.preparedstatement;
import java.sql.resultset;
import java.sql.sqlexception;


public class dbconn {
  //三属性、四方法
  
  //三大核心接口
  private connection conn = null;
  private preparedstatement pstmt = null;
  private resultset rs = null;
  
  //四个方法
  //method1: 创建数据库的连接
  public connection getconntion(){    
    try {
      //1: 加载连接驱动,java反射原理
      class.forname(config.class_name);
      //2:创建connection接口对象,用于获取mysql数据库的连接对象。三个参数:url连接字符串  账号 密码
      string url = config.database_url+"://"+config.server_ip+":"+config.server_port+"/"+config.database_sid;
      conn = drivermanager.getconnection(url,config.username,config.password);
    } catch (classnotfoundexception e) {
      e.printstacktrace();
    } catch (sqlexception e) {
      e.printstacktrace();
    }  
    return conn;
  }
  
  
  //method2:关闭数据库的方法
  public void closeconn(){
    if(rs!=null){
      try {
        rs.close();
      } catch (sqlexception e) {
        e.printstacktrace();
      }
    }
    if(pstmt!=null){
      try {
        pstmt.close();
      } catch (sqlexception e) {
        e.printstacktrace();
      }
    }
    if(conn!=null){
      try {
        conn.close();
      } catch (sqlexception e) {
        e.printstacktrace();
      }
    }
  }

  
  //method3: 专门用于发送增删改语句的方法
  public int execother(preparedstatement pstmt){
    try {
      //1、使用statement对象发送sql语句
      int affectedrows = pstmt.executeupdate();
      //2、返回结果
      return affectedrows;
    } catch (sqlexception e) {
      e.printstacktrace();
      return -1;
    }
  }


  //method4: 专门用于发送查询语句
  public resultset execquery(preparedstatement pstmt){
    try {
      //1、使用statement对象发送sql语句
      rs = pstmt.executequery();
      //2、返回结果
      return rs;
    } catch (sqlexception e) {
      e.printstacktrace();
      return null;
    }
  }

}

平时的用上面的代码能够解决一些简单的crud的应用了,但是还有很多限制,比如每次程序拿连接都要new,这样就给系统加大了负担,没有事务,没有datasource等等,今天看见一哥们在园里面写的一篇用反射解决直接以对象参数的方式crud,这个我以前也写过,没写完,主要是自己想写一个通用的dbutil,最后研究来研究去,发现越来越和hibernate里面的simplejdbctemplate接近了,所以就直接去看hibernate的源码了,加上那段时间有些事,没有时间,就将这件事闲置起来了,现在把这个东西补上,也给自己回顾一下下

basedao类

package com.employees.dao;
import java.io.inputstream;
import java.lang.reflect.method;
import java.lang.reflect.parameterizedtype;
import java.sql.connection;
import java.sql.date;
import java.sql.preparedstatement;
import java.sql.resultset;
import java.util.arraylist;
import java.util.iterator;
import java.util.list;

import com.employees.dbutil.dbconn;

public class basedao<t> {
  
  dbconn conn = new dbconn();
  private connection connection = null;
  
  @suppresswarnings("unused")
  private class<t> persistentclass;
  
  @suppresswarnings("unchecked")
  public basedao() {
    initconnection();
    //获得参数化类型    
    parameterizedtype type = (parameterizedtype)getclass().getgenericsuperclass();
    persistentclass = (class<t>)type.getactualtypearguments()[0];
  }
  
  
  /**
   * 获得数据库连接
   */
  public void initconnection() {
    connection = conn.getconntion();      
  }
  
  
  /**
   * 保存
   */
  public void save(t entity) throws exception{
    //sql语句,insert into table name (
    string sql = "insert into " + entity.getclass().getsimplename().tolowercase() + "(";
    
    //获得带有字符串get的所有方法的对象
    list<method> list = this.matchpojomethods(entity,"get");
    
    iterator<method> iter = list.iterator();
    
    //拼接字段顺序 insert into table name(id,name,email,
    while(iter.hasnext()) {
      method method = iter.next();
      sql += method.getname().substring(3).tolowercase() + ",";
    }
    
    //去掉最后一个,符号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);
    
    //获得预编译对象的引用
    preparedstatement statement = connection.preparestatement(sql);
    
    int i = 0;
    //把指向迭代器最后一行的指针移到第一行.
    iter = list.iterator();
    while(iter.hasnext()) {
      method method = iter.next();
      //此初判断返回值的类型,因为存入数据库时有的字段值格式需要改变,比如string,sql语句是'"+abc+"'
      if(method.getreturntype().getsimplename().indexof("string") != -1) {
        statement.setstring(++i, this.getstring(method, entity));
      } else if(method.getreturntype().getsimplename().indexof("date") != -1){
        statement.setdate(++i, this.getdate(method, entity));
      } else if(method.getreturntype().getsimplename().indexof("inputstream") != -1) {
        statement.setasciistream(++i, this.getblob(method, entity),1440);
      } else {
        statement.setint(++i, this.getint(method, entity));
      }
    }
    //执行
    conn.execother(statement);
    //关闭连接
    conn.closeconn();
  }
  
  
  /**
   * 修改
   */
  public void update(t entity) throws exception{
    string sql = "update " + entity.getclass().getsimplename().tolowercase() + " set ";
    
    //获得该类所有get方法对象集合
    list<method> list = this.matchpojomethods(entity,"get");
    
    //临时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) {
        //把id字段的对象存放到一个变量中,然后在集合中删掉.
        idmethod = tempmethod;
        iter.remove();
      //如果方法名去掉set/get字符串以后与pojo + "id"想符合(大小写不敏感),则视为id
      } else if((entity.getclass().getsimplename() + "id").equalsignorecase(tempmethod.getname().substring(3))) {
        idmethod = tempmethod;
        iter.remove();        
      }
    }
    
    //把迭代指针移到第一位
    iter = list.iterator();
    while(iter.hasnext()) {
      tempmethod = iter.next();
      sql += tempmethod.getname().substring(3).tolowercase() + "= ?,";
    }
    
    //去掉最后一个,符号
    sql = sql.substring(0,sql.lastindexof(","));
    
    //添加条件
    sql += " where " + idmethod.getname().substring(3).tolowercase() + " = ?";
    
    //sql拼接完成,打印sql语句
    system.out.println(sql);
    
    preparedstatement statement = this.connection.preparestatement(sql);
    
    int i = 0;
    iter = list.iterator();
    while(iter.hasnext()) {
      method method = iter.next();
      //此初判断返回值的类型,因为存入数据库时有的字段值格式需要改变,比如string,sql语句是'"+abc+"'
      if(method.getreturntype().getsimplename().indexof("string") != -1) {
        statement.setstring(++i, this.getstring(method, entity));
      } else if(method.getreturntype().getsimplename().indexof("date") != -1){
        statement.setdate(++i, this.getdate(method, entity));
      } else if(method.getreturntype().getsimplename().indexof("inputstream") != -1) {
        statement.setasciistream(++i, this.getblob(method, entity),1440);
      } else {
        statement.setint(++i, this.getint(method, entity));
      }      
    }
    
    //为id字段添加值
    if(idmethod.getreturntype().getsimplename().indexof("string") != -1) {
      statement.setstring(++i, this.getstring(idmethod, entity));
    } else {
      statement.setint(++i, this.getint(idmethod, entity));
    }
    
    //执行sql语句
    statement.executeupdate();
        
        //关闭预编译对象
        statement.close();
        
        //关闭连接
        connection.close();
  }
  
  
  /**
   * 删除
   */
  public void delete(t entity) throws exception{
    string sql = "delete from " + entity.getclass().getsimplename().tolowercase() + " where ";
    
    //存放字符串为"id"的字段对象
    method idmethod = null;
    
    //取得字符串为"id"的字段对象
    list<method> list = this.matchpojomethods(entity, "get");
    iterator<method> iter = list.iterator();
    while(iter.hasnext()) {
      method tempmethod = iter.next();
      //如果方法名中带有id字符串并且长度为2,则视为id.
      if(tempmethod.getname().lastindexof("id") != -1 && tempmethod.getname().substring(3).length() == 2) {
        //把id字段的对象存放到一个变量中,然后在集合中删掉.
        idmethod = tempmethod;
        iter.remove();
      //如果方法名去掉set/get字符串以后与pojo + "id"想符合(大小写不敏感),则视为id
      } else if((entity.getclass().getsimplename() + "id").equalsignorecase(tempmethod.getname().substring(3))) {
        idmethod = tempmethod;
        iter.remove();        
      }
    }
    
    sql += idmethod.getname().substring(3).tolowercase() + " = ?";
    
    preparedstatement statement = this.connection.preparestatement(sql);
    
    //为id字段添加值
    int i = 0;
    if(idmethod.getreturntype().getsimplename().indexof("string") != -1) {
      statement.setstring(++i, this.getstring(idmethod, entity));
    } else {
      statement.setint(++i, this.getint(idmethod, entity));
    }    
    
    //执行
    conn.execother(statement);
    //关闭连接
    conn.closeconn();
  }
  
  
  /**
   * 通过id查询
   */
  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) + " = ?";
    
    //封装语句完毕,打印sql语句
    system.out.println(sql);
    
    //获得连接
    preparedstatement statement = this.connection.preparestatement(sql);
    
    //判断id的类型
    if(object instanceof integer) {
      statement.setint(1, (integer)object);
    } else if(object instanceof string){
      statement.setstring(1, (string)object);
    }
    
    //执行sql,取得查询结果集.
    resultset rs = conn.execquery(statement);
    
    //记数器,记录循环到第几个字段
    int i = 0;
        
    //把指针指向迭代器第一行
    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 if(method.getparametertypes()[0].getsimplename().indexof("inputstream") != -1) {
          this.setblob(method, entity, rs.getblob(method.getname().substring(3).tolowercase()).getbinarystream());
        } else {
          this.setint(method, entity, rs.getint(method.getname().substring(3).tolowercase()));
        }  
      }
    }
    
    //关闭结果集
    rs.close();
        
    //关闭预编译对象
    statement.close();
    
    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;
  }
  
  
  /**
   * 方法返回类型为int或integer类型时,返回的sql语句值.对应get
   */
  public integer getint(method method, t entity) throws exception{
    return (integer)method.invoke(entity, new object[]{});
  }
  
  /**
   * 方法返回类型为string时,返回的sql语句拼装值.比如'abc',对应get
   */
  public string getstring(method method, t entity) throws exception{
    return (string)method.invoke(entity, new object[]{});
  }
  
  /**
   * 方法返回类型为blob时,返回的sql语句拼装值.对应get
   */
  public inputstream getblob(method method, t entity) throws exception{
    return (inputstream)method.invoke(entity, new object[]{});
  }
  
  
  /**
   * 方法返回类型为date时,返回的sql语句拼装值,对应get
   */
  public date getdate(method method, t entity) throws exception{
    return (date)method.invoke(entity, new object[]{});
  }
  
  
  /**
   * 参数类型为integer或int时,为entity字段设置参数,对应set
   */
  public integer setint(method method, t entity, integer arg) throws exception{
    return (integer)method.invoke(entity, new object[]{arg});
  }
  
  /**
   * 参数类型为string时,为entity字段设置参数,对应set
   */
  public string setstring(method method, t entity, string arg) throws exception{
    return (string)method.invoke(entity, new object[]{arg});
  }
  
  /**
   * 参数类型为inputstream时,为entity字段设置参数,对应set
   */
  public inputstream setblob(method method, t entity, inputstream arg) throws exception{
    return (inputstream)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});
  }
}

employeesdao继承basedao,可以直接使用父类的方法,增加了代码的复用

package com.employees.dao;

import java.util.arraylist;
import java.util.list;
import com.employees.po.employees;

public class employeesdao extends basedao<employees> {

  // 添加员工信息的操作
  public boolean addemployees(final employees employees) throws exception {
    save(employees);
    return true;
  }

  // 将员工信息添加到表格中
  public list<employees> addemployees(int id) throws exception {
    list<employees> lstemployees = new arraylist<employees>();
    employees employees = findbyid(id);
    // 将当前封转好的数据装入对象中
    lstemployees.add(employees);
    return lstemployees;
  }

  public void deleteemp(final employees entity) throws exception {
    this.delete(entity);
  }

  public void updateemp(final employees entity) throws exception {
    this.update(entity);
  }


}

po层的代码就不贴了,现在用junit4做一下测试

package com.employees.dao;

import org.junit.test;

import com.employees.po.employees;

public class employeesdaotest {

  @test
  public void testadd() throws exception {
    employees emp = new employees();
    emp.setpname("tly");
    emp.setpsex("男");
    emp.setpbeliefs("xxxxx");
    emp.setpaddr("天河");
    emp.setphobby("打篮球");
    emp.setpsubject("计算机");
    emp.setptel("123456");
    employeesdao dao = new employeesdao();
    dao.addemployees(emp);
  }
  @test
  public void testupdate() throws exception {
    employeesdao dao = new employeesdao();
    employees emp = dao.findbyid(14);
    emp.setptel("999999");
    dao.updateemp(emp);
  }
  @test
  public void testdelete() throws exception {
    employeesdao dao = new employeesdao();
    employees emp = dao.findbyid(15);
    dao.deleteemp(emp);
  }

}

经过测试,这三个方法都能正常运行,时间仓促,有些代码是参考其他哥们的,有些地方可能考虑的不是很全面或者有些代码会有冗余,basedao中做通用crud操作没有写全,要是哪位小伙伴有兴趣,可以接下去写写,比如查询,批量化操作等等,如果测试通过的话,记得给我发一份啊,呵呵

以上这篇简单通用jdbc辅助类封装(实例)就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持移动技术网。

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网