2017-02-25 69 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; 
}