Search code examples
javadatabasejdbcencapsulationsetter

Java JDBC - ResultSet and encapsulation. Many fields, way too many setters and getters to manage. Is there a better technique?


I am writing a java program that reads a database file and shows the records on a gui screen, using JDBC and ResultSet. The database file has hundreds of fields. That means that if I separate gui and database processing in two class files and use encapsulation, I’d end up with hundreds of setter and getter methods (one for each field). Is there a better way of doing this?

Note that I have used setters and getters for this purpose and found out that it can get really hard to manage. I also have seen articles that advocate avoiding to use setters and getters altogether but did not find a concrete example of such technique for database management.

Thanks I appreciate your help.


Solution

  • One way is to just store each row into a Map.

    To do this, you can retrieve the column names using ResultSetMetaData (key = column name) or you can just retrieve the column values using the column index (key = index). ResultSet can deal with it both ways.

    Then, your result will look like a List<Map> structure.