java中的结果集转换器

java中的结果集转换器,java,design-patterns,jdbc,Java,Design Patterns,Jdbc,在JDBC中是否有任何方法可以直接将结果集内容获取到列表中。我需要像下面这样的通用的东西 不用说,只需要选择查询(因为我的应用程序用于报告目的) } 列值类: import java.io.Serializable; public class ColumnValueDTO implements Serializable { private String propertyName; private String propertyValue; private stati

在JDBC中是否有任何方法可以直接将结果集内容获取到列表中。我需要像下面这样的通用的东西

不用说,只需要选择查询(因为我的应用程序用于报告目的)

}

列值类:

import java.io.Serializable;

public class ColumnValueDTO implements Serializable {

    private String propertyName;
    private String propertyValue;

    private static final long serialVersionUID = -4915109169715618102L;

    /**
     * @return the propertyName
     */
    public String getPropertyName() {
       return propertyName;
    }
    /**
     * @param propertyName the propertyName to set
     */
    public void setPropertyName(String propertyName) {
         this.propertyName = propertyName;
    }
    /**
     * @return the propertyValue
     */
    public String getPropertyValue() {
        return propertyValue;
    }
    /**
     * @param propertyValue the propertyValue to set
     */
    public void setPropertyValue(String propertyValue) {
        this.propertyValue = propertyValue;
    }

    public String toString(){
        return "Property ::  "+this.propertyName+"   Value :: "+this.propertyValue;
    }


}
对于获取BLOB和CLOB(在java中是
字节[]
),您应该更改方法签名
getValueByType(对象值、类类型、类域字段类型)
,并在if语句中再添加一个
。大概是这样的:

if (domainFieldType.equals(byte[].class)) {
    retvalue= System.arraycopy(...);
}

在您的示例中,您有一个方法

public static Object executeQuery(PreparedStatement inPstmt,String pDomainClassName)throws SQLException,Exception{

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

 // the body of method

return outResultList;

}
publicstaticobjectexecutequery(PreparedStatement inpsmt,String pDomainClassName)抛出SQLException,Exception{
List outResultList=新建ArrayList();
//方法主体
返回结果列表;
}
方法声明返回对象,但在实现中返回列表是错误的。但是为了得到你想要的,你可以使用一种通用的方法

public static <T> List<T> executeQuery(PreparedStatement inPstmt,Class<T> type) throws Exception{
    return (List<T>) executeQuery(inPstmt, type.getName()); //Here you will get a warning. 
}
public static List executeQuery(PreparedStatement inpsmt,类类型)引发异常{
return(List)executeQuery(inpsmt,type.getName());//在这里您将得到一个警告。
}
--

编辑:

请注意,在您的代码中几乎没有问题。值分析器消耗资源,在比较字符串和类型时无法正常工作。而且代码的可编辑性很难,因为您在使用之前声明了对象

 /**
     * Generates DB column and java Domain class property mapping
     * 
     * @param pInputClassName
     *                       java Domain class, fully qualified name(package+java class)
     * @return
     *                       Map<String,ColumnMappingDTO>, mapping of DB column and Java Doamin class property
     * @throws Exception
     *                       if pInputClassName is not loaded properly
     */
    private static Map<String, ColumnMappingDTO> initColumnMappings(String pInputClassName) throws Exception {

        Map<String, ColumnMappingDTO> outMappingDetails = new HashMap<String, ColumnMappingDTO>();

        try {

            for (Field vField : getFields(pInputClassName)) {
                for (Annotation vAnnotation : vField.getDeclaredAnnotations()) {
                    if (vAnnotation instanceof Column) {
                        ColumnMappingDTO vColumnMappingDTO = createColumnMapping(vField, (Column) vAnnotation);
                        outMappingDetails.put(vColumnMappingDTO.getColumnName(), vColumnMappingDTO);
                    }
                }
            }
        } catch (Exception ex) {
            System.out.println("caught Exception in initColumnMappings() as  " + ex);
            throw ex;
        }

        return outMappingDetails;
    }


    /**
     * @param vField
     * @param vAnnotation
     * @return
     */
    private static ColumnMappingDTO createColumnMapping(Field vField, Column vAnnotation) {
        ColumnMappingDTO vColumnMappingDTO = new ColumnMappingDTO();
            vColumnMappingDTO.setPropertyName(vField.getName());
            vColumnMappingDTO.setColumnName(vAnnotation.name());
        return vColumnMappingDTO;
    }


    /**
     * @param pInputClassName
     * @return
     * @throws ClassNotFoundException
     */
    private static Field[] getFields(String pInputClassName) throws ClassNotFoundException {
        //try loading Domain Object Class
        return Class.forName(pInputClassName).getDeclaredFields();
    }



    /**
     * Executes sql passed inform of PreparedStatement inPstmt and generated List genere as String pDomainClassName
     * 
     * @param inPstmt
     *               Sql to be executed inform of PreparedStatement
     * @param pDomainClassName
     *               fully qualified Class name of DTO
     * @return
     *               Object, later to be type casted to List<pDomainClassName>
     * @throws Exception
     *               When Mapping is not missing or done wrong 
     * 
     */

    public static Object executeQuery(PreparedStatement inPstmt, String pDomainClassName) throws SQLException, Exception {
        return executeQuery(inPstmt, Class.forName(pDomainClassName));
    }

    public static <T> List<T>  executeQuery(PreparedStatement inPstmt, Class<T> domainClass) throws SQLException, Exception {

        List<T> outResultList = new ArrayList<T>();
        ResultSet mRSet = null;
        try {

            // generate DB Column and Domain Class property mapping
            Map<String, ColumnMappingDTO> mMappingDetailsMap = initColumnMappings(domainClass.getName());

            // execute sql
            mRSet = inPstmt.executeQuery();

            if (mRSet == null) {
                return Collections.EMPTY_LIST;
            }

            List<String> mColumnNamesList = getColumnNameList(mRSet);


            while (mRSet.next()) {
                List<ColumnValueDTO> mColumnValuesList = new ArrayList<ColumnValueDTO>();

                for (String columnHeader : mColumnNamesList) {

                    if (mMappingDetailsMap.containsKey(columnHeader)) {
                        ColumnValueDTO mColumnValueDTO = new ColumnValueDTO();
                            mColumnValueDTO.setPropertyName(mMappingDetailsMap.get(columnHeader).getPropertyName());
                            mColumnValueDTO.setPropertyValue(mRSet.getString(mMappingDetailsMap.get(columnHeader).getColumnName()));
                        mColumnValuesList.add(mColumnValueDTO);
                    }
                }

                //
                T domainObj = createDomainObject(mColumnValuesList, domainClass);

                // Add Object to out List
                outResultList.add(domainObj);
            }
        } catch (Exception ex) {
            System.out.println(" caught in executeQuery() " + ex);
            throw ex;
        } finally {

            // release resources
            try {
                mRSet.close();
            } catch (SQLException e) {
                System.out.println(" caught in Exception while closing ResultSet " + e);
                throw e;
            }

        }
        return outResultList;
    }


    /**
     * @param mColumnNamesList
     * @param mRSet
     * @return 
     * @throws SQLException
     */
    private static List<String> getColumnNameList(ResultSet mRSet) throws SQLException {

        ResultSetMetaData mRsetMt = mRSet.getMetaData();

        if(mRsetMt == null){
            return Collections.EMPTY_LIST;
        }

        List<String> mColumnNamesList = new ArrayList<String>();

        // generate SELECT columns list
        for (int i = 0; i < mRsetMt.getColumnCount(); i++) {
            mColumnNamesList.add(mRsetMt.getColumnName(i + 1));
        }

        return mColumnNamesList;
    }


    private static Object createDomainObject(List<ColumnValueDTO> columnValuesList, String vDoaminClass) throws Exception {

        Class<?> domainClassObj = Class.forName(vDoaminClass);
        return createDomainObject(columnValuesList, domainClassObj);

    }

    private static <T> T createDomainObject(List<ColumnValueDTO> columnValuesList, Class<T> domainClassObj) throws Exception {

        T domainObj = null;

        try {

            domainObj = domainClassObj.newInstance();

            for (ColumnValueDTO columnDTO : columnValuesList) {

                if (columnDTO == null) {
                    continue;
                }

                Field domainDataField = domainClassObj.getDeclaredField(columnDTO.getPropertyName());
                    domainDataField.setAccessible(true);

                Object valueByType = parseValueByType(columnDTO.getPropertyValue(), domainDataField.getType());
                domainDataField.set(domainObj, valueByType);
            }

        } catch (Exception e) {
            System.out.println(" Caught " + e.getClass().getSimpleName() + " in createDomainObject() " + e);
            throw e;
        }

        return domainObj;
    }

    private static Object parseValueByType(String value, Type type) throws Exception{

        if(value == null) {
            return null;
        }

        try{

            if(Integer.TYPE.equals(type)){
                return Integer.parseInt(value);
            }

            if(Double.TYPE.equals(type)){
                return Double.parseDouble(value);
            }

            if(Float.TYPE.equals(type)){
                return Float.parseFloat(value);
            }

            if(Short.TYPE.equals(type)) {
                return Short.parseShort(value);
            }

            if(Long.TYPE.equals(type)) {
                return Long.parseLong(value);
            }

            if(java.sql.Timestamp.class.equals(type)) {
                return java.sql.Timestamp.valueOf(value);
            }

            if(java.sql.Date.class.equals(type)) {
                return java.sql.Date.valueOf(value);
            }

            if(String.class.equals(type)) {
                return value; 
            }

            if(Character.TYPE.equals(type)) {
                if(value.length() == 1) {
                    return value.charAt(0);
                }

                if(value.length() == 0) {
                    return '\0';
                }
                throw new IllegalStateException("");
            }

        }catch(Exception ex){
            System.out.println(" Caught Exception in getValueByType() "+ex);
            throw ex;
        }

        throw new IllegalArgumentException("Could not find the resolver for type " + type);
    }


     public static class ColumnValueDTO implements Serializable {

            private String propertyName;
            private String propertyValue;

            private static final long serialVersionUID = -4915109169715618102L;

            /**
             * @return the propertyName
             */
            public String getPropertyName() {
               return propertyName;
            }
            /**
             * @param propertyName the propertyName to set
             */
            public void setPropertyName(String propertyName) {
                 this.propertyName = propertyName;
            }
            /**
             * @return the propertyValue
             */
            public String getPropertyValue() {
                return propertyValue;
            }
            /**
             * @param propertyValue the propertyValue to set
             */
            public void setPropertyValue(String propertyValue) {
                this.propertyValue = propertyValue;
            }

            public String toString(){
                return "Property ::  "+this.propertyName+"   Value :: "+this.propertyValue;
            }


        }


     public static class ColumnMappingDTO {

         private String columnName;
         private String propertyName;
         private String dataType;

         /**
          * @return the columnName
          */
         public String getColumnName() {
             return columnName;
         }
         /**
          * @param columnName the columnName to set
          */
         public void setColumnName(String columnName) {
             this.columnName = columnName;
         }
         /**
          * @return the dataType
          */
         public String getDataType() {
             return dataType;
         }
         /**
          * @param dataType the dataType to set
          */
         public void setDataType(String dataType) {
             this.dataType = dataType;
         }
         /**
          * @return the propertyName
          */
         public String getPropertyName() {
             return propertyName;
         }
         /**
          * @param propertyName the propertyName to set
          */
         public void setPropertyName(String propertyName) {
             this.propertyName = propertyName;
         }

         public String toString(){

             return "Database Column :: "+this.columnName+"  Java Property :: "+this.propertyName+"   Java Datatype :: "+this.dataType;
         }
     }

     private static class Column {

        /**
         * @return
         */
        public String name() {
            // TODO Auto-generated method stub
            return null;
        }

     }
/**
*生成DB列和java域类属性映射
* 
*@param pInputClassName
*java域类,完全限定名(包+java类)
*@返回
*映射、DB列映射和Java Doamin类属性
*@抛出异常
*如果pInputClassName未正确加载
*/
私有静态映射initColumnMappings(字符串pInputClassName)引发异常{
Map outMappingDetails=新建HashMap();
试一试{
用于(字段vField:getFields(pInputClassName)){
对于(注释注释:vField.getDeclaredAnnotations()){
if(列的表示法实例){
ColumnMappingDTO vColumnMappingDTO=创建ColumnMapping(vField,(Column)表示法);
outMappingDetails.put(vColumnMappingDTO.getColumnName(),vColumnMappingDTO);
}
}
}
}捕获(例外情况除外){
System.out.println(“initColumnMappings()中捕获的异常为“+ex”);
掷骰子;
}
返回outMappingDetails;
}
/**
*@param vField
*@param-vAnnotation
*@返回
*/
私有静态ColumnMappingDTO到createColumnMapping(字段vField,列表示法){
ColumnMappingDTO vColumnMappingDTO=新ColumnMappingDTO();
vColumnMappingDTO.setPropertyName(vField.getName());
vColumnMappingDTO.setColumnName(vAnnotation.name());
返回vColumnMappingDTO;
}
/**
*@param pInputClassName
*@返回
*@ClassNotFoundException
*/
私有静态字段[]getFields(字符串pInputClassName)引发ClassNotFoundException{
//尝试加载域对象类
返回类.forName(pInputClassName).getDeclaredFields();
}
/**
*执行sql传递的PreparedStatement inpsmt通知,并将生成的列表genere作为字符串pDomainClassName
* 
*@param inpsmt
*要执行的Sql通知PreparedStatement
*@param pDomainClassName
*DTO的完全限定类名
*@返回
*对象,稍后将类型转换为列表
*@抛出异常
*映射未丢失或未出错时
* 
*/
公共静态对象executeQuery(PreparedStatement InputStmt,字符串pDomainClassName)引发SQLException,Exception{
返回executeQuery(inpsmt,Class.forName(pDomainClassName));
}
公共静态列表executeQuery(PreparedStatement inpsmt,Class domainClass)抛出SQLException,Exception{
List outResultList=新建ArrayList();
结果集mRSet=null;
试一试{
//生成DB列和域类属性映射
Map mMappingDetailsMap=initColumnMappings(domainClass.getName());
//执行sql
mRSet=inpsmt.executeQuery();
if(mRSet==null){
返回集合。空_列表;
}
List MColumnNameList=getColumnNameList(mRSet);
while(mRSet.next()){
List mColumnValuesList=新的ArrayList();
for(字符串列标题:mColumnNamesList){
if(mMappingDetailsMap.containsKey(columnHeader)){
ColumnValueDTO mColumnValueDTO=新ColumnValueDTO();
mColumnValueDTO.setPropertyName(mMappingDetailsMap.get(columnHeader.getPropertyName());
mColumnValueDTO.setPropertyValue(mRSet.getString(mMappingDetailsMap.get(columnHeader.getColumnName());
mColumnValuesList.add(mColumnValueDTO);
}
}
//
T domainObj=createDomainObject(mColumnValuesList,domainClass);
//将对象添加到输出列表
add(domainObj);
}
}捕获(例外情况除外){
System.out.println(“捕获在executeQuery()中”+ex);
掷骰子;
}最后{
//释放资源
试一试{
mRSet.close();
}捕获(SQLE异常){
System.out.println(“关闭结果集时捕获异常”+e);
投掷e;
}
}
返回结果列表;
}
/**
*@param mcolumnameslist
*@param-mRSet
*@返回
*@t
public static Object executeQuery(PreparedStatement inPstmt,String pDomainClassName)throws SQLException,Exception{

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

 // the body of method

return outResultList;

}
public static <T> List<T> executeQuery(PreparedStatement inPstmt,Class<T> type) throws Exception{
    return (List<T>) executeQuery(inPstmt, type.getName()); //Here you will get a warning. 
}
 /**
     * Generates DB column and java Domain class property mapping
     * 
     * @param pInputClassName
     *                       java Domain class, fully qualified name(package+java class)
     * @return
     *                       Map<String,ColumnMappingDTO>, mapping of DB column and Java Doamin class property
     * @throws Exception
     *                       if pInputClassName is not loaded properly
     */
    private static Map<String, ColumnMappingDTO> initColumnMappings(String pInputClassName) throws Exception {

        Map<String, ColumnMappingDTO> outMappingDetails = new HashMap<String, ColumnMappingDTO>();

        try {

            for (Field vField : getFields(pInputClassName)) {
                for (Annotation vAnnotation : vField.getDeclaredAnnotations()) {
                    if (vAnnotation instanceof Column) {
                        ColumnMappingDTO vColumnMappingDTO = createColumnMapping(vField, (Column) vAnnotation);
                        outMappingDetails.put(vColumnMappingDTO.getColumnName(), vColumnMappingDTO);
                    }
                }
            }
        } catch (Exception ex) {
            System.out.println("caught Exception in initColumnMappings() as  " + ex);
            throw ex;
        }

        return outMappingDetails;
    }


    /**
     * @param vField
     * @param vAnnotation
     * @return
     */
    private static ColumnMappingDTO createColumnMapping(Field vField, Column vAnnotation) {
        ColumnMappingDTO vColumnMappingDTO = new ColumnMappingDTO();
            vColumnMappingDTO.setPropertyName(vField.getName());
            vColumnMappingDTO.setColumnName(vAnnotation.name());
        return vColumnMappingDTO;
    }


    /**
     * @param pInputClassName
     * @return
     * @throws ClassNotFoundException
     */
    private static Field[] getFields(String pInputClassName) throws ClassNotFoundException {
        //try loading Domain Object Class
        return Class.forName(pInputClassName).getDeclaredFields();
    }



    /**
     * Executes sql passed inform of PreparedStatement inPstmt and generated List genere as String pDomainClassName
     * 
     * @param inPstmt
     *               Sql to be executed inform of PreparedStatement
     * @param pDomainClassName
     *               fully qualified Class name of DTO
     * @return
     *               Object, later to be type casted to List<pDomainClassName>
     * @throws Exception
     *               When Mapping is not missing or done wrong 
     * 
     */

    public static Object executeQuery(PreparedStatement inPstmt, String pDomainClassName) throws SQLException, Exception {
        return executeQuery(inPstmt, Class.forName(pDomainClassName));
    }

    public static <T> List<T>  executeQuery(PreparedStatement inPstmt, Class<T> domainClass) throws SQLException, Exception {

        List<T> outResultList = new ArrayList<T>();
        ResultSet mRSet = null;
        try {

            // generate DB Column and Domain Class property mapping
            Map<String, ColumnMappingDTO> mMappingDetailsMap = initColumnMappings(domainClass.getName());

            // execute sql
            mRSet = inPstmt.executeQuery();

            if (mRSet == null) {
                return Collections.EMPTY_LIST;
            }

            List<String> mColumnNamesList = getColumnNameList(mRSet);


            while (mRSet.next()) {
                List<ColumnValueDTO> mColumnValuesList = new ArrayList<ColumnValueDTO>();

                for (String columnHeader : mColumnNamesList) {

                    if (mMappingDetailsMap.containsKey(columnHeader)) {
                        ColumnValueDTO mColumnValueDTO = new ColumnValueDTO();
                            mColumnValueDTO.setPropertyName(mMappingDetailsMap.get(columnHeader).getPropertyName());
                            mColumnValueDTO.setPropertyValue(mRSet.getString(mMappingDetailsMap.get(columnHeader).getColumnName()));
                        mColumnValuesList.add(mColumnValueDTO);
                    }
                }

                //
                T domainObj = createDomainObject(mColumnValuesList, domainClass);

                // Add Object to out List
                outResultList.add(domainObj);
            }
        } catch (Exception ex) {
            System.out.println(" caught in executeQuery() " + ex);
            throw ex;
        } finally {

            // release resources
            try {
                mRSet.close();
            } catch (SQLException e) {
                System.out.println(" caught in Exception while closing ResultSet " + e);
                throw e;
            }

        }
        return outResultList;
    }


    /**
     * @param mColumnNamesList
     * @param mRSet
     * @return 
     * @throws SQLException
     */
    private static List<String> getColumnNameList(ResultSet mRSet) throws SQLException {

        ResultSetMetaData mRsetMt = mRSet.getMetaData();

        if(mRsetMt == null){
            return Collections.EMPTY_LIST;
        }

        List<String> mColumnNamesList = new ArrayList<String>();

        // generate SELECT columns list
        for (int i = 0; i < mRsetMt.getColumnCount(); i++) {
            mColumnNamesList.add(mRsetMt.getColumnName(i + 1));
        }

        return mColumnNamesList;
    }


    private static Object createDomainObject(List<ColumnValueDTO> columnValuesList, String vDoaminClass) throws Exception {

        Class<?> domainClassObj = Class.forName(vDoaminClass);
        return createDomainObject(columnValuesList, domainClassObj);

    }

    private static <T> T createDomainObject(List<ColumnValueDTO> columnValuesList, Class<T> domainClassObj) throws Exception {

        T domainObj = null;

        try {

            domainObj = domainClassObj.newInstance();

            for (ColumnValueDTO columnDTO : columnValuesList) {

                if (columnDTO == null) {
                    continue;
                }

                Field domainDataField = domainClassObj.getDeclaredField(columnDTO.getPropertyName());
                    domainDataField.setAccessible(true);

                Object valueByType = parseValueByType(columnDTO.getPropertyValue(), domainDataField.getType());
                domainDataField.set(domainObj, valueByType);
            }

        } catch (Exception e) {
            System.out.println(" Caught " + e.getClass().getSimpleName() + " in createDomainObject() " + e);
            throw e;
        }

        return domainObj;
    }

    private static Object parseValueByType(String value, Type type) throws Exception{

        if(value == null) {
            return null;
        }

        try{

            if(Integer.TYPE.equals(type)){
                return Integer.parseInt(value);
            }

            if(Double.TYPE.equals(type)){
                return Double.parseDouble(value);
            }

            if(Float.TYPE.equals(type)){
                return Float.parseFloat(value);
            }

            if(Short.TYPE.equals(type)) {
                return Short.parseShort(value);
            }

            if(Long.TYPE.equals(type)) {
                return Long.parseLong(value);
            }

            if(java.sql.Timestamp.class.equals(type)) {
                return java.sql.Timestamp.valueOf(value);
            }

            if(java.sql.Date.class.equals(type)) {
                return java.sql.Date.valueOf(value);
            }

            if(String.class.equals(type)) {
                return value; 
            }

            if(Character.TYPE.equals(type)) {
                if(value.length() == 1) {
                    return value.charAt(0);
                }

                if(value.length() == 0) {
                    return '\0';
                }
                throw new IllegalStateException("");
            }

        }catch(Exception ex){
            System.out.println(" Caught Exception in getValueByType() "+ex);
            throw ex;
        }

        throw new IllegalArgumentException("Could not find the resolver for type " + type);
    }


     public static class ColumnValueDTO implements Serializable {

            private String propertyName;
            private String propertyValue;

            private static final long serialVersionUID = -4915109169715618102L;

            /**
             * @return the propertyName
             */
            public String getPropertyName() {
               return propertyName;
            }
            /**
             * @param propertyName the propertyName to set
             */
            public void setPropertyName(String propertyName) {
                 this.propertyName = propertyName;
            }
            /**
             * @return the propertyValue
             */
            public String getPropertyValue() {
                return propertyValue;
            }
            /**
             * @param propertyValue the propertyValue to set
             */
            public void setPropertyValue(String propertyValue) {
                this.propertyValue = propertyValue;
            }

            public String toString(){
                return "Property ::  "+this.propertyName+"   Value :: "+this.propertyValue;
            }


        }


     public static class ColumnMappingDTO {

         private String columnName;
         private String propertyName;
         private String dataType;

         /**
          * @return the columnName
          */
         public String getColumnName() {
             return columnName;
         }
         /**
          * @param columnName the columnName to set
          */
         public void setColumnName(String columnName) {
             this.columnName = columnName;
         }
         /**
          * @return the dataType
          */
         public String getDataType() {
             return dataType;
         }
         /**
          * @param dataType the dataType to set
          */
         public void setDataType(String dataType) {
             this.dataType = dataType;
         }
         /**
          * @return the propertyName
          */
         public String getPropertyName() {
             return propertyName;
         }
         /**
          * @param propertyName the propertyName to set
          */
         public void setPropertyName(String propertyName) {
             this.propertyName = propertyName;
         }

         public String toString(){

             return "Database Column :: "+this.columnName+"  Java Property :: "+this.propertyName+"   Java Datatype :: "+this.dataType;
         }
     }

     private static class Column {

        /**
         * @return
         */
        public String name() {
            // TODO Auto-generated method stub
            return null;
        }

     }