利用java反射创建通用的数据库查询方法

来源:互联网 发布:淘宝鹰眼 编辑:程序博客网 时间:2024/04/30 06:34

很好的一文章,百度文库看到的


package Dao;

 

import java.lang.reflect.InvocationTargetException;

import java.lang.reflect.Method;

import java.sql.Connection;

import java.sql.PreparedStatement;

import java.sql.ResultSet;

import java.sql.ResultSetMetaData;

import java.sql.SQLException;

import java.sql.Statement;

import java.util.ArrayList;

import java.util.List;

/**

 * 使用java反射,创建通用的增删改方法,与通用的查询方法

 * @authorAnjet

 *

 */

public class BaseDao {

 

      private Connectionconn;

      private Statementsta;

      private PreparedStatementps;

      private ResultSetrs;

      private ResultSetMetaDataRSM;

 

      public String getSql() {

           returnsql;

      }

 

      public void setSql(String sql){

           this.sql = sql;

      }

 

      public Object[]getParam() {

           returnparam;

      }

 

      public void setParam(Object[]param) {

           this.param = param;

      }

 

      private Stringsql;

      private Object[]param;

/**

 *  填充sql语句,形成完整sql语句

 * @param param参数数组

 */

      private voidsetParament(Object[] param) {

           for (int i = 0; i <param.length; i++) {

                 try {

                      ps.setObject(i + 1,param[i]);

                 }catch (SQLException e) {

                      // TODO Auto-generated catch block

                      e.printStackTrace();

                 }

           }

      }

/**

 *  根据数据库中的列名获取其在实体类中对应的setter方法

 * @param colName 列名

 * @param type  数据类型

 * @param cs    实体类

 * @return 实体类方法

 */

      private Method  getMethodByColName(String colName,Stringtype,Class  cs){

            //用来记录在实体类中对应的setter方法

           MethodMD=null;

            //methodName用来记录方法名

            String methodName="set";

            /**

             * 对列名进行处理

             */

            //1.如果列名中有“_”,则对列名根据“_”进行分割

            String[] cols=colName.split("_");

            for(int i=0;i<cols.length;i++){

                  if(cols[i].length()>1){

                       //如果截取的每一段的字符串的长度大于1

                       //则将每一段的第一个字母转为大写

                       methodName+=cols[i].toUpperCase().substring(0, 1)+cols[i].toLowerCase().substring(1);

                  }else{

                       methodName+=cols[i].toUpperCase();

                  }

            }

            if(type=="java.sql.Timestamp"){

                  type="java.util.Date";

            }

            try {

                  //记录列在中实体类中的setter方法

                 MD=cs.getDeclaredMethod(methodName,Class.forName(type));

           }catch(NoSuchMethodException e) {

                 // TODO Auto-generated catch block

                 e.printStackTrace();

           }catch (SecurityExceptione) {

                 // TODO Auto-generated catch block

                 e.printStackTrace();

           }catch(ClassNotFoundException e) {

                 // TODO Auto-generated catch block

                 e.printStackTrace();

           }

            return MD;

      }

 

      /**

       * 通用的增删改方法

       *

       * @param sql

       * @return

       */

      public boolean UID(String sql) {

           boolean boo =false;

           try {

                 int n;

                 conn =ConnectionManager.getConn();

                 if (param ==null || param.length == 0) {

                      sta = conn.createStatement();

                      n= sta.executeUpdate(sql);

                 }else {

                       ps = conn.prepareStatement(sql);

                      this.setParament(param);

                      n= ps.executeUpdate();

                 }

 

                 if (n > 0) {

                      boo= true;

                 }

           }catch (SQLException e) {

                 // TODO Auto-generated catch block

                 e.printStackTrace();

           }finally {

                 ConnectionManager.CloseAll(conn,sta, ps, rs);

           }

           return boo;

 

      }

 

      /**

       * 通用的查询操作方法

       *

       * @param sql

       * @param cls

       * @return

       * @throws IllegalAccessException

       * @throws InstantiationException

       * @throws InvocationTargetException

       * @throws IllegalArgumentException

       */

      public List<Object>AllSelect(String sql,Class cls) throwsInstantiationException, IllegalAccessException, IllegalArgumentException,InvocationTargetException {

           List<Object>list = new ArrayList<Object>();

           Objectobj = null;

           try {

                 conn =ConnectionManager.getConn();

                 if (param ==null || param.length == 0) {

                      sta = conn.createStatement();

                      rs = sta.executeQuery(sql);

                 }else {

                      ps = conn.prepareStatement(sql);

                      this.setParament(param);

                      rs = ps.executeQuery();

                 }

                 //getMetaData()方法获取返回数据的类型,编号,属性

                 RSM=rs.getMetaData();

                 //建立方法数组,用来存储实体类方法

                 Method[] ms=new Method[RSM.getColumnCount()];//RSM.getColumnCount()方法检索RSM对象中列的总数

                 //根据列名获取方法名

                 for(int i=0;i<ms.length;i++){

                      //getColumnName()获取列名

                      StringcolName=RSM.getColumnName(i+1);

                       //获取列的数据类型

                      Stringtype=RSM.getColumnClassName(i+1);

                      //将每一列在实体类中对应的赋值方法添加进入方法数组

                      ms[i]=this.getMethodByColName(colName,type, cls);

                 }

                 while(rs.next()){

                      //newInstance()弱类型,低效率,只能调用无参构造方法,

                      //使obj实体化

                      obj=cls.newInstance();

                      //通过反射。给实体类属性赋值

                      for(int i=0;i<ms.length;i++){

                            ms[i].invoke(obj,rs.getObject(i+1));

                      }

                      //将赋值后的对象添加入数组

                      list.add(obj);

                 }

           }catch (SQLException e) {

                 // TODO Auto-generated catch block

                 e.printStackTrace();

           }finally {

                 ConnectionManager.CloseAll(conn,sta, ps, rs);

           }

           return list;

      }

 

}

 

0 0
原创粉丝点击