java - 从数据库中获取数据并以pojo对象的形式返回

标签 java database jdbc pojo

我有一个返回类型为 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/

相关文章:

java - 来自 Guice 的 "Please wait until after injection has completed to use this object"错误

java - "Install new software error"与 eclipse 靛蓝/朱诺 RCP

Java垃圾收集器

database - 提高 PostgreSQL 中的 OFFSET 性能

jdbc - 使用cassandra-jdbc-1.2.1 jar创建表时出错

java - thrift api java客户端与HBase连接

mysql - SQL数据插入列错误

mysql - 如何反序列化 postmeta 并在 wp_query 中将其用于搜索过滤器

java - 为什么 PreparedStatement.setNull 需要 sqlType?

java - MySQL 创建过程脚本在 Workbench 中运行但不在 java conn.createStatement().execute 中运行