Search code examples
javadatabasejdbcpojo

Get data from database and return it in form of pojo object


I have a method whose return type is customer which is a pojo. When I get required customerId from database I want to return the customer object with the corresponding data of that customerId. This means it has customer name, address etc. How to proceed for this?

public class Customer verifyCustomerId(cutomerId){
    statement = connection.createStatement();

    resultSet = statement.executeQuery("select customerid from customer");

    while (resultSet.next()) {
        if (cutomerId == resultSet.getInt(1)) {

            // return data corresponding to this id in the form of object of pojo customer

        }
    }

    return null;
}

Solution

  • You can create a Customer object and set your attribute in it like this :

    Customer custemer;
    
    if (resultSet.next()) {
       customer = new Customer(resultSet.getInt("customerid"));
    }
    
    return custemer;
    

    If you want to get one result you don't need to use while(..) you can make an if instead and your query should have a condition "select customerid from customer where ..." because your query can get multiple results, if you want to get a List you can use while like this :

    List<Customer> listCustemer = new ArrayList<>();
    
    while (resultSet.next()) {
       listCustemer.add(new Customer(resultSet.getInt("customerid")));
    }
    
    return listCustemer;
    

    EDIT

    You can change your constructor and sett your fields you want like name, address and ..., like this : Customer(int id, String name, String address, ...)

    So you can use this constructor to create a new Object like so :

    listCustemer.add(new Customer(resultSet.getInt("customerid"), 
                     resultSet.getString("name"), resultSet.getString("address"), ...));