[英]Outputing certain elements from a returned database returned List
I am querying a database to return a list of values based on an input string; 我正在查询数据库以根据输入字符串返回值列表; and these list of values are displayed in a searchbox for the user.
这些值列表将显示在用户的搜索框中。 The issue is, my returned lists are being displayed as objects instead of a list of names.
问题是,我返回的列表显示为对象而不是名称列表。 Attached are snippets of code to illustrate my point
随附的代码段说明了我的观点
my retrieve method 我的检索方法
public List<EmployeeDetails> getEmployeeByName(String employeeName) {
List<EmployeeDetails> list=new ArrayList<EmployeeDetails>();
Connection c=null;
String sql=("SELECT * FROM employee_table WHERE UPPER(employeeName) LIKE ? ORDER BY employeeName");
try{
c = ConnectionHelper.getConnection();
PreparedStatement ps=c.prepareStatement(sql);
ps.setString(1, "%" + employeeName.toUpperCase() + "%");
ResultSet rs=ps.executeQuery();
while(rs.next()){
list.add(new EmployeeDetails (rs.getInt("employeeid"),
rs.getString("employeeName"),
rs.getString("employeeAddress"),
rs.getString("employeeAge"),
rs.getString("nationality"),
rs.getString("salaryRate")));
}
}catch (SQLException e) {
e.printStackTrace();
try {
throw new Exception(e);
} catch (Exception e1) {
e1.printStackTrace();
}
} finally {
ConnectionHelper.close(c);
}
return **list**;
}
i intend the searchbox be populated with only the names of the returned objects, not the raw encapsulated object. 我打算只用返回对象的名称填充搜索框,而不用原始封装的对象填充。 How do i go about this?
我该怎么办? Any help/pointers would be highly appreciated
任何帮助/指针将不胜感激
The result of this method must be getting used somewhere. 此方法的结果必须在某处使用。 Wherever that is, you need to do something like this:
无论在哪里,都需要执行以下操作:
class EmployeeDAO
{
// Your method doing data access
public List<EmployeeDetail> getEmployeeByName(String employeeName) {
...
return list;
}
}
class EmployeeController
{
public void searchByName( String employeeName )
{
List<EmployeeDetail> employeeDetails = employeeDao.getEmployeeByName( employeeName );
Map<String, EmployeeDetail> searchResults = new HashMap<String, EmployeeDetail>();
// Use employeeNames in the search box
for( EmployeeDetail employeeDetail : employeeDetails )
{
searchResults.put( employeeDetail.getEmployeeName(), employeeDetail );
}
// I don't know how to return objects for Flex/BlazeDS, so this is more Spring MVC style
view.put( "searchResults", searchResults );
}
}
Two other suggestions: 另外两个建议:
EmployeeDetails
class to EmployeeDetail
(singular). EmployeeDetails
类为EmployeeDetail
(单数)。 That way, collections of EmployeeDetail
objects can use names like employeeDetails
(plural). EmployeeDetail
对象的集合可以使用诸如employeeDetails
(复数)之类的名称。 getEmployeesByName
since you don't guarantee there's only one employee returned. getEmployeesByName
因为您不能保证只有一名员工返回。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.