Daniel Morgan
Daniel Morgan

Reputation: 772

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

 }
 }.....

Upvotes: 5

Views: 218

Answers (2)

stepanian
stepanian

Reputation: 11433

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

Upvotes: 2

Ajay George
Ajay George

Reputation: 11875

As mentioned by Jigar Joshi in the comments, an ORM framework such as Hibernate would be a good choice here.

Here is an example to get you started.

http://docs.jboss.org/hibernate/orm/4.1/quickstart/en-US/html_single/#hibernate-gsg-tutorial-basic-test-list

Upvotes: 0

Related Questions