I have an object called employee which has a long list of attributes, I am retriving the values from database and need to put them into the employee object, I am doing the following but as the code is so long I am wondering if there is any shortcut to it.
Employee emp = new Employee();
try {
ps = con.prepareStatement("select * from Employee WHERE username = ?");
ps.setString(1, username);
ResultSet r = ps.executeQuery();
if (r.next()) {
// 12 lines to put values into employee object need to be shorter
emp.setID(r.getInt(1));
emp.setTitle(r.getString(2));
emp.setFname(r.getString(3));
emp.setLname(r.getString(4));
emp.setMobile(r.getString(5));
emp.setPhone(r.getString(6));
emp.setEmail(r.getString(7));
emp.setPosition(r.getString(8));
emp.setUsername(r.getString(9));
emp.setPassword(r.getString(10));
emp.setQuestion(r.getString(11));
emp.setAnswer(r.getString(12));
}
}.....
Use Apache Commons BeanProcessor. It has two VERY useful methods just for this called toBean and toBeanList.
In this case, you would simply do this:
if (r.next()) {
BeanProcessor bp = new BeanProcessor();
emp = bp.toBean(r, Employee.class);
}
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