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 retrieve users I use a ResultSet. I want to map each of the columns back to the user attributes but the way I am doing it seems terribly inefficient. For example I am doing:
//ResultSet rs; while(rs.next()) { String uid = rs.getString("UserId"); String fname = rs.getString("FirstName"); ... ... ... User u = new User(uid,fname,...); //ArrayList<User> users users.add(u); }
i.e I retrieve all the columns and then create user objects by inserting all the column values into the User constructor.
Does anyone know of a faster, neater, way of doing this?
Code to map ResultSet to Object - ResultSetMapper.The function mapRersultSetToObject maps resultset to an ArrayList of type SamplePojo. It first checks if the outputClass has the 'Entity' annotation. The core logic of this function is that, it gets the attributes in the outputClass having annotation 'Column'.
But we can make this object to move forward and backward direction by passing either TYPE_SCROLL_INSENSITIVE or TYPE_SCROLL_SENSITIVE in createStatement(int,int) method as well as we can make this object as updatable by: Statement stmt = con. createStatement(ResultSet.
The ResultSet interface declares getter methods (for example, getBoolean and getLong ) for retrieving column values from the current row. You can retrieve values using either the index number of the column or the alias or name of the column.
If you don't want to use any JPA provider such as OpenJPA or Hibernate, you can just give Apache DbUtils a try.
http://commons.apache.org/proper/commons-dbutils/examples.html
Then your code will look like this:
QueryRunner run = new QueryRunner(dataSource); // Use the BeanListHandler implementation to convert all // ResultSet rows into a List of Person JavaBeans. ResultSetHandler<List<Person>> h = new BeanListHandler<Person>(Person.class); // Execute the SQL statement and return the results in a List of // Person objects generated by the BeanListHandler. List<Person> persons = run.query("SELECT * FROM Person", h);
No need of storing resultSet values into String and again setting into POJO class. Instead set at the time you are retrieving.
Or best way switch to ORM tools like hibernate instead of JDBC which maps your POJO object direct to database.
But as of now use this:
List<User> users=new ArrayList<User>(); while(rs.next()) { User user = new User(); user.setUserId(rs.getString("UserId")); user.setFName(rs.getString("FirstName")); ... ... ... users.add(user); }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With