How to get values ​​from ResultSet as a whole?

I need to get the values ​​from the ResultSet in order to use them through reflexion to call the constructor. I tried with Class.cast (Object), but always get 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 that I already had.

+4
source share
1 answer

Even if you can make it work, there is a long-term nightmare of maintaining that the order of the arguments in the Object constructor may not match the order of the columns in the ResultSet (table in RDB). for example, if your Person object has a constructor named 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 the code that I saw to handle this problem more generally, they use reflection of a domain object (e.g. Person) to get property names (in my case, they looked at setters, not at constructors, YMMV), and then tried to map them to ResultSet column names using ResultSet.getMetaData() .

+1
source

Source: https://habr.com/ru/post/1488886/


All Articles