Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get values from a ResultSet generically?

I need to retrieve the values from a ResultSet to use them via reflexion to invoke a constructor. I was trying with Class.cast(Object), but I always get an InvalidCastException.

This is what I have:

    Object[] args = new Object[count];
    Class<?>[] arr = co.getParameterTypes(); 
    for(i = 0; i<args.length; i++){

        args[i] = arr[i].cast(rs.getObject(i+1));
    }

    Object t;

    try {
        t = co.newInstance(args);
    } catch (Exception e) {
        throw new RuntimeException(e); 
    }

    return (T)t;

co is the constructor, and rs is the ResultSet I already have.

like image 511
João Caselli Avatar asked Nov 13 '22 02:11

João Caselli


1 Answers

Even if you can get this to work, there's a long-term maintenance nightmare that the order of the arguments in the Object's constructor may not match the order of the columns in the ResultSet (the table in the RDB). e.g., if your Person object has a constructor taking a firstName, lastName, the order of the columns in the DB Table may not match. It could be LAST_NAME, FIRST_NAME, or even FIRST_NAME, SOME_COLUMN_YOU_DONT_CARE_ABOUT, LAST_NAME.

In code I have seen to handle this issue more generically, they use reflection upon the domain object (e.g. Person) to get the property names (in my case, they looked at setters, not constructors, YMMV), then try to match them to the ResultSet column names, using ResultSet.getMetaData().

like image 136
user949300 Avatar answered Nov 14 '22 22:11

user949300