Spring MVC-step-by-step[2]

[入库:2006年2月23日] [更新:2007年3月24日]

本文简介:


Lets go over the two DAO methods in this class. First, getProductList() creates a query object that will retrieve all the products. This query is executed and the results are passed back as a list of Products. At the end of the class we can see the definition for this query class. I have implemented it as an inner class since we are not going to reference it anywhere else, but I could just as well have made it a separate class. This query class extends MappingSqlQuery, which is a central class in Spring's JDBC framework. The idea behind this class is that you have to specify a SQL query when this class is created, and you are also responsible for implementing the mapRow method to map the data from each row into a class that represents the entity you are retrieving in your query. That's it, that's all you have to provide. The rest is managed by the framework. In the constructor of the ProductQuery class I pass in the data source. This data source will be provided in a similar fashion to the way we wired up the business objects in Part 2, so we don't have to worry about retrieving a data source in our DAO class. In the constructor I also define the SQL query that we will use to retrieve the products. The mapRow method will be called once for each row returned by the query. It creates a new Product and populates it based on the data retrieved from the current row of the resultset. You should not call getNext on the resultset, it is all handled by the framework. This is another example of an Inversion of Control solution.

The second method increasePrice is utilizing an SqlUpdate class. This class is passed the data source and an SQL update statement with placeholders for parameters. Same syntax as a prepared statement in JDBC. In fact, that is what SqlUpdate creates behind the scenes. For the parameters, we have to give them a name and declare what type they are so that the framework can set them before the prepared statement is executed. After all parameters have been declared, we “compile?? the statement in JDO fashion. This will signal that we are done declaring parameters, and the framework will check to make sure that we have a matching declaration for each placeholder in the SQL statement. Next we declare an Object array that will hold the parameter values that we are going to pass in to the prepared statement. This array gets passed into the update method of SqlUpdate. The update method does return the count of rows affected.
ProductManager.java改动如下所示:

本文关键:Spring MVC-step-by-step
  相关方案
Google
 

本站最佳浏览方式为 分辨率 1024x768 IE 6.0(或更高版本的 IE浏览器)

go top