2017-02-25 70 views
2

我有一种方法,其返回类型是customer,它是pojo。当我从数据库中获得要求customerId时,我想要返回客户对象与相应的数据customerId。这意味着它有客户名称,地址等。如何继续?从数据库中获取数据并以pojo对象的形式返回

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; 
} 
+0

您是否在此逻辑开始时有customerId,还是您需要先找到它? – JamesB

回答

3

您可以创建一个Customer对象,并设置你的属性,它是这样的:

Customer custemer; 

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

return custemer; 

如果你想得到一个结果,你不需要使用while(..)你可以使一个if inst EAD和你query应该有一个条件"select customerid from customer where ...",因为你的查询可以得到多个结果,如果你想获得你可以使用while像这样的列表:

List<Customer> listCustemer = new ArrayList<>(); 

while (resultSet.next()) { 
    listCustemer.add(new Customer(resultSet.getInt("customerid"))); 
} 

return listCustemer; 

编辑

你可以改变你的构造和SETT你想,如姓名,地址和......你的领域,如:Customer(int id, String name, String address, ...)

所以,你可以使用此构造函数来创建新的对象,像这样:

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

是的,你是正确的,但我有许多客户实体的属性没有任何其他方式,或者我应该去这个吗? –

+0

@payalgala你可以创建一个构造函数,它具有多个像这样的'新客户(par,par2,par2,par2,par2 ..)' –

+0

我不认为这回答了这个问题。没有提及获取其他客户字段如姓名和地址。 – JamesB

3

您的SQL语句需要选择您要从数据库中取回的数据。您当前的语句将返回customer表中所有行的customerId。

更改声明:

PreparedStatement ps = con.prepareStatement("select name from customer where customerId = ?"); 
ps.setInt(1, cutomerId); 
ResultSet rs = ps.executeQuery(); 
while (rs.next()) { 
    // use ResultSet to populate Customer pojo 
} 

我从客户表此选择的名字,但它假定这样的列存在。修改它以选择你想要的列。

这里是用预处理教程: http://docs.oracle.com/javase/tutorial/jdbc/basics/prepared.html

这里是一个理由来使用它们: How does a PreparedStatement avoid or prevent SQL injection?

1

我没有看到任何阻止您获取这些详细信息的内容,您必须做的是编辑您试图从数据库中获取的QUERY。

public class Customer verifyCustomerId(cutomerId){ 
statement = connection.createStatement(); 
CustomerPoJo customer; 
resultSet = statement.executeQuery("select * from customer"); 

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

// Fill in the details accordingly 
     String customername = resultSet.getString(2); 
     String customeraddress = resultSet.getString(3); 
     ... 

     customer = new CustomerPoJo(); 
     customer.setCustomerId(customerId); 
     customer.setCustomerName(customername); 
     customer.setCustomerAddress(customeraddress); 
     ... 

    } 
} 
// Instead send your customer object 
return customer; 
}