Mapping a JDBC ResultSet to an object

前端 未结 8 1197
生来不讨喜
生来不讨喜 2020-12-04 18:14

I have a user class that has 16 attributes, things such as firstname, lastname, dob, username, password etc... These are all stored in a MySQL database and when I want to re

8条回答
  •  有刺的猬
    2020-12-04 18:46

    import java.util.ArrayList;
    import java.util.HashMap;
    import java.util.List;
    import java.util.Map;
    import org.json.simple.JSONObject;
    import com.google.gson.Gson;
    
    public class ObjectMapper {
    
    //generic method to convert JDBC resultSet into respective DTo class
    @SuppressWarnings("unchecked")
    public static Object mapValue(List> rows,Class className) throws Exception
    {
    
            List response=new ArrayList<>(); 
            Gson gson=new Gson();
    
            for(Map row:rows){
            org.json.simple.JSONObject jsonObject = new JSONObject();
            jsonObject.putAll(row);
            String json=jsonObject.toJSONString();
            Object actualObject=gson.fromJson(json, className);
            response.add(actualObject);
            }
            return response;
    
        }
    
        public static void main(String args[]) throws Exception{
    
            List> rows=new ArrayList>(); 
    
            //Hardcoded data for testing
            Map row1=new HashMap();
            row1.put("name", "Raja");
            row1.put("age", 22);
            row1.put("location", "India");
    
    
            Map row2=new HashMap();
            row2.put("name", "Rani");
            row2.put("age", 20);
            row2.put("location", "India");
    
            rows.add(row1);
            rows.add(row2);
    
    
            @SuppressWarnings("unchecked")
            List res=(List) mapValue(rows, Dto.class);
    
    
        }
    
        }
    
        public class Dto {
    
        private String name;
        private Integer age;
        private String location;
    
        //getters and setters
    
        }
    
    
    

    Try the above code .This can be used as a generic method to map JDBC result to respective DTO class.

    提交回复
    热议问题