I created a new bean called client with Id, Name, LastName and Address fields. I created the model and the view of course. My model returns a list of all the clients. And this one is working fine.
But I need a model where I can select only one specific client filtered by Id. Can anybody tell me what I need to change (besides the SQL statement) inside this model so I get only one client according to filter (id) criteria from SQL?
{
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;
}
}
Well, I guess you already have a class with a method that you invoke to retrieve all the cliets, right?
Well, now add another method, but this time a method that receives the client Id as parameter:
You will need a secondary SQL statement, since the logic in the first one is for retrieving all records. Something like:
Using a JDBC PreparedStatement you can easily replace the ? for the actual parameter being received by your API.
You can also consider abstracting your mapping strategy so that you can use it for both methods:
You can also have a ClientsMapper that uses this single client mapper to retrieve all clients.