Mapping a JDBC ResultSet to an object

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

    Use Statement Fetch Size , if you are retrieving more number of records. like this.

    Statement statement = connection.createStatement();
    statement.setFetchSize(1000); 
    

    Apart from that i dont see an issue with the way you are doing in terms of performance

    In terms of Neat. Always use seperate method delegate to map the resultset to POJO object. which can be reused later in the same class

    like

    private User mapResultSet(ResultSet rs){
         User user = new User();
         // Map Results
         return user;
    }
    

    If you have the same name for both columnName and object's fieldName , you could also write reflection utility to load the records back to POJO. and use MetaData to read the columnNames . but for small scale projects using reflection is not an problem. but as i said before there is nothing wrong with the way you are doing.

    0 讨论(0)
  • 2020-12-04 18:52

    using DbUtils...

    The only problem I had with that lib was that sometimes you have relationships in your bean classes, DBUtils does not map that. It only maps the properties in the class of the bean, if you have other complex properties (refering other beans due to DB relationship) you'd have to create "indirect setters" as I call, which are setters that put values into those complex properties's properties.

    0 讨论(0)
提交回复
热议问题