繁体   English   中英

仅选择一条记录(Javabean,setAttribute,getAttribute,SQL,servlet)

[英]Selecting only one record (Javabean, setAttribute, getAttribute, SQL, servlet)

我使用IdNameLastNameAddress字段创建了一个名为client的新bean。 我创建了模型和视图。 我的模型返回所有​​客户的列表。 而且这个工作正常。

但是我需要一个模型,在该模型中,我只能选择一个由Id过滤的特定客户端。 谁能告诉我在此模型内需要更改的内容(SQL语句除外),以便根据SQL的过滤器(id)标准仅获得一个客户端?

{
    Connection connection = getDatabaseConnection();
    request.setAttribute("clientList", getClientList(connection));
    closeDatabaseConnection(connection);
}

private ArrayList<Client> getClientList(Connection con)
{
    String sqlstr = "SELECT * FROM Clients";
    PreparedStatement stmt = null;
    ResultSet rs = null;
    ArrayList<Client> clients = new ArrayList<Client>();

    try
    {
        stmt = con.prepareStatement(sqlStr);
        rs = stmt.executeQuery();

        while (rs.next())
        {
            Client client = new Client();
            client.setId(rs.getInt("Id"));
            client.setName(rs.getString("Name"));
            client.setLastName(rs.getString("LastName"));
            client.setAddress(rs.getString("Address"));

            clients.add(client);
        }

        rs.close();
        stmt.close();
    }
    catch (SQLException sqle)
    {
        sqle.printStackTrace();
    }
    finally
    {
        return clients;
    }
}

除了sql语句,您还意味着什么?您必须在查询中添加where子句,我认为没有其他可能的情况。

好吧,我想您已经有了一个类,该类具有您调用来检索所有片段的方法,对吗?

好了,现在添加另一个方法,但是这次是一个接收客户端ID作为参数的方法:

public List<Client> getAllClients();
public Client getClientById(int clientId);

您将需要一个辅助SQL语句,因为第一个语句中的逻辑是用于检索所有记录。 就像是:

"select clientId, clientName, ... from clients where clientId=?"

使用JDBC PreparedStatement可以轻松替换?。 API收到的实际参数。

您还可以考虑抽象化映射策略,以便可以将其用于两种方法:

class ClientMapper implements SqlMapper<Client> {
    @Override
    public Client map(ResultSet rs) throws SQLException {
       Client client = new Client();
       client.setId(rs.getInt("Id"));
       client.setName(rs.getString("Name"));
       client.setLastName(rs.getString("LastName"));
       client.setAddress(rs.getString("Address"));
       return client;
    }
}

您还可以拥有一个使用此单个客户端映射器的ClientsMapper来检索所有客户端。

class ClientsMapper implements SqlMapper<List<Client>>{
   @Override
   public List<Client> map(ResultSet rs){
     List<Client> result = new ArrayList<>();
     ClientMapper mapper = new ClientMapper();
     while(rs.next()){
        result.add(mapper.map(rs));
     }
     return result;
   }
}

好了,您可以使用另一种方法,该方法根据您提供的id作为参数返回单个客户端。

 public Client getClientById(int id){
    //fetch the client data using the id

    //make a local Client object
    Client c = new Client();

    //populate c based on the values you get from your database.

    //return this local object of Client
    return c;

 }

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM