我有一个返回类型为 customer 的方法,它是一个 pojo。当我从数据库中获取所需的 customerId
时,我想返回具有该 customerId
的相应数据的客户对象。这意味着它有客户名称、地址等。如何进行此操作?
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;
}
最佳答案
您可以创建一个 Customer
对象并在其中设置您的属性,如下所示:
Customer custemer;
if (resultSet.next()) {
customer = new Customer(resultSet.getInt("customerid"));
}
return custemer;
如果你想得到一个结果,你不需要使用 while(..)
你可以做一个 if
而不是你的 query
应该有一个条件 "select customerid from customer where ..."
因为你的查询可以得到多个结果,如果你想得到一个列表你可以使用 while
这个:
List<Customer> listCustemer = new ArrayList<>();
while (resultSet.next()) {
listCustemer.add(new Customer(resultSet.getInt("customerid")));
}
return listCustemer;
编辑
您可以更改您的构造函数并设置您想要的字段,例如名称、地址和...,如下所示:Customer(int id, String name, String address, ...)
所以你可以像这样使用这个构造函数来创建一个新的对象:
listCustemer.add(new Customer(resultSet.getInt("customerid"),
resultSet.getString("name"), resultSet.getString("address"), ...));
关于java - 从数据库中获取数据并以pojo对象的形式返回,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42454958/