Encapsulate the result of the query into an object through reflection to return the list collection

Reprint address: http://yjck.iteye.com/blog/1221160

    public List<Object> getList(String sql,Object[] params,Object obj){  
            ResultSet rs = null;  
            if(params == null){  
               rs = this.getRs(sql);  
            }else{  
               rs = this.getRs(sql, params);  
            }  
            List<Object> list = new ArrayList<Object>();  
            try {  
                while(rs.next()){  
                int i = 1;  
                Object inst =  obj.getClass().newInstance();  
                Field[] fields = inst.getClass().getDeclaredFields();  
                    for(Field field : fields){  
                        String setStr = field.getName().substring(0, 1).toUpperCase();  
                        String setMehtodName = "set"+setStr+field.getName().substring(1);  
                        Method setMethod = obj.getClass().getMethod(setMehtodName, new Class[]{field.getType()});  
                        setMethod.invoke(inst, new Object[]{rs.getString(i)});  
                        i++;  
                    }  
                    list.add(inst);  
                }  
            } catch (SecurityException e) {  
                e.printStackTrace ();  
            } catch (SQLException e) {  
                e.printStackTrace ();  
            } catch (IllegalArgumentException e) {  
                e.printStackTrace ();  
            } catch (IllegalAccessException e) {  
                e.printStackTrace ();  
            } catch (InvocationTargetException e) {  
                e.printStackTrace ();  
            } catch (NoSuchMethodException e) {  
                e.printStackTrace ();  
            } catch (InstantiationException e) {  
                e.printStackTrace ();  
            }  
            return list;  
              
        }  

Roughly explain: After obtaining the ResultSet, encapsulate it into a LIST collection, which can be obtained directly in hibernate. Of course, I have not seen how it is implemented in hibernate. I am just one of my implementations here, and there are some restrictions.

1. Obtaining the bean object is the inst here;

2. Get all the field fields of the bean object, that is, those fields defined;

3. Construct the set method name of each field;

4. Set the results from the Resultset to the Bean object

5. Put the bean object into the List collection

6.return List collection

Restriction: Make sure that the order of the Bean objects is the same as the order of each field detected by the written query statement, otherwise, it will be a slap in the face!


Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324954101&siteId=291194637