0

我正在查询数据库以根据输入字符串返回值列表;这些值列表显示在用户的搜索框中。问题是,我返回的列表显示为对象而不是名称列表。附上代码片段来说明我的观点

我的检索方法

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**;




}

我打算只填充返回对象的名称,而不是原始封装对象的名称。我该怎么做?任何帮助/指针将不胜感激

4

1 回答 1

0

这种方法的结果必须在某处得到使用。无论在哪里,您都需要执行以下操作:

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 );
    }   
}

另外两个建议:

  1. EmployeeDetails将类重命名为EmployeeDetail(单数)。这样,EmployeeDetail对象集合可以使用employeeDetails(复数)之类的名称。
  2. 将您的方法重命名为,getEmployeesByName因为您不能保证只有一名员工返回。
于 2013-04-06T23:01:46.607 回答