Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add results to an object with long list of fields?

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));

 }
 }.....
like image 999
Daniel Morgan Avatar asked Nov 04 '22 04:11

Daniel Morgan


1 Answers

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);
}
like image 113
stepanian Avatar answered Nov 15 '22 00:11

stepanian