Mapping a JDBC ResultSet to an object

前端 未结 8 1253
生来不讨喜
生来不讨喜 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:28

    Complete solution using @TEH-EMPRAH ideas and Generic casting from Cast Object to Generic Type for returning

    import annotations.Column;
    import java.lang.reflect.Field;
    import java.lang.reflect.InvocationTargetException;
    import java.sql.SQLException;
    import java.util.*;
    
    public class ObjectMapper {
    
        private Class clazz;
        private Map fields = new HashMap<>();
        Map errors = new HashMap<>();
    
        public DataMapper(Class clazz) {
            this.clazz = clazz;
    
            List fieldList = Arrays.asList(clazz.getDeclaredFields());
            for (Field field : fieldList) {
                Column col = field.getAnnotation(Column.class);
                if (col != null) {
                    field.setAccessible(true);
                    fields.put(col.name(), field);
                }
            }
        }
    
        public T map(Map row) throws SQLException {
            try {
                T dto = (T) clazz.getConstructor().newInstance();
                for (Map.Entry entity : row.entrySet()) {
                    if (entity.getValue() == null) {
                        continue;  // Don't set DBNULL
                    }
                    String column = entity.getKey();
                    Field field = fields.get(column);
                    if (field != null) {
                        field.set(dto, convertInstanceOfObject(entity.getValue()));
                    }
                }
                return dto;
            } catch (IllegalAccessException | InstantiationException | NoSuchMethodException | InvocationTargetException e) {
                e.printStackTrace();
                throw new SQLException("Problem with data Mapping. See logs.");
            }
        }
    
        public List map(List> rows) throws SQLException {
            List list = new LinkedList<>();
    
            for (Map row : rows) {
                list.add(map(row));
            }
    
            return list;
        }
    
        private T convertInstanceOfObject(Object o) {
            try {
                return (T) o;
            } catch (ClassCastException e) {
                return null;
            }
        }
    }
    

    and then in terms of how it ties in with the database, I have the following:

    // connect to database (autocloses)
    try (DataConnection conn = ds1.getConnection()) {
    
        // fetch rows
        List> rows = conn.nativeSelect("SELECT * FROM products");
    
        // map rows to class
        ObjectMapper objectMapper = new ObjectMapper<>(Product.class);
        List products = objectMapper.map(rows);
    
        // display the rows
        System.out.println(rows);
    
        // display it as products
        for (Product prod : products) {
            System.out.println(prod);
        }
    
    } catch (Exception e) {
        e.printStackTrace();
    }
    

提交回复
热议问题