从返回的数据库输出某些元素返回List

时间:2013-04-06 22:13:27

标签: java mysql jdb

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

我的检索方法

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




}

我打算在搜索框中只填充返回对象的名称,而不是原始的封装对象。 我该怎么做?任何帮助/指针都将受到高度赞赏

1 个答案:

答案 0 :(得分: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,因为您不保证只返回一名员工。