4、实现数据库持久
(23)建立数据库表
(译者:原文采用的是HSQL,在这里使用MySQL,版本号是4.0.20a)
下面是创建数据库表products的SQL脚本,使用的数据库是test:
/*!40014 SET @OLD_UNIQUE_CHECKS=@@UNIQUE_CHECKS, UNIQUE_CHECKS=0 */;
/*!40014 SET @OLD_FOREIGN_KEY_CHECKS=@@FOREIGN_KEY_CHECKS, FOREIGN_KEY_CHECKS=0 */;
/*!40101 SET @OLD_SQL_MODE=@@SQL_MODE, SQL_MODE=NO_AUTO_VALUE_ON_ZERO */;
CREATE DATABASE /*!32312 IF NOT EXISTS*/ `test`;
USE `test`;
CREATE TABLE `products` (
`id` int(11) NOT NULL default '0',
`description` varchar(255) default '',
`price` decimal(15,2) default '0.00',
PRIMARY KEY (`id`),
KEY `products_description` (`description`)
) TYPE=MyISAM;
INSERT INTO `products` (`id`,`description`,`price`) VALUES (1,'Lamp','5.78'),(2,'Table','75.29'),(3,'Chair','22.81');
/*!40101 SET SQL_MODE=@OLD_SQL_MODE */;
/*!40014 SET FOREIGN_KEY_CHECKS=@OLD_FOREIGN_KEY_CHECKS */;
/*!40014 SET UNIQUE_CHECKS=@OLD_UNIQUE_CHECKS */;
不同的数据库SQL语句的学法上会有些不同,请做适当调整
(24)创建实现JDBC的DAO
l 首先是DAO接口ProductManagerDao,提供了列表产品和增长产品价格的功能
package db;
import bus.Product;
import java.util.List;
public interface ProductManagerDao {
public List getProductList();
public void increasePrice(Product prod, int pct);
}
l ProductManagerDaoJdbc类实现ProductManagerDao接口
package db;
import bus.Product;
import java.util.List;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Types;
import javax.sql.DataSource;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.jdbc.object.MappingSqlQuery;
import org.springframework.jdbc.object.SqlUpdate;
import org.springframework.jdbc.core.SqlParameter;
public class ProductManagerDaoJdbc implements ProductManagerDao {
/** Logger for this class and subclasses */
protected final Log logger = LogFactory.getLog(getClass());
private DataSource ds;
public List getProductList() {
logger.info("Getting products!");
ProductQuery pq = new ProductQuery(ds);
return pq.execute();
}
public void increasePrice(Product prod, int pct) {
logger.info("Increasing price by " + pct + "%");
SqlUpdate su =
new SqlUpdate(ds, "update products set price = price * (100 + ?) / 100 where id = ?");
su.declareParameter(new SqlParameter("increase", Types.INTEGER));
su.declareParameter(new SqlParameter("ID", Types.INTEGER));
su.compile();
Object[] oa = new Object[2];
oa[0] = new Integer(pct);
oa[1] = new Integer(prod.getId());
int count = su.update(oa);
logger.info("Rows affected: " + count);
}
public void setDataSource(DataSource ds) {
this.ds = ds;
}
class ProductQuery extends MappingSqlQuery {
ProductQuery(DataSource ds) {
super(ds, "SELECT id, description, price from products");
compile();
}
protected Object mapRow(ResultSet rs, int rowNum) throws SQLException {
Product prod = new Product();
prod.setId(rs.getInt("id"));
prod.setDescription(rs.getString("description"));
prod.setPrice(new Double(rs.getDouble("price")));
return prod;
}
}
}
l 这里使用了Spring JDBC框架,其好处是不需要担心连接和语句的打开和关闭,不需要捕捉异常(除非你想要这么做)
l ProductQuery是一个内类,扩展MappingSqlQuery类,封装SQL查询;在构造方法中传递DataSource(在Bean配置中定义)和查询SQL语句给父类;通过实现mapRow()方法,可以将查询结果的每一行数据映射到表示实体(通常是JavaBean)
l getProductList()方法的实现是创建一个查询对象ProductQuery,通过调用其execute()方法返回查询结果:映射好的Product对象列表
l 在increasePrice()方法中,使用SqlUpdate创建带参数的更新语句(需要传递DataSource);这里需要调用declareParameter()方法定义参数类型,并以对象数组的形式传递参数值给update()方法来执行更新语句,并返回影响的行数
l Product类需要增加id属性来保存主键值
package bus;
import java.io.Serializable;
public class Product implements Serializable {
private int id;
private String description;
private Double price;
public void setId(int i) {
id = i;
}
public int getId() {
return id;
}
public void setDescription(String s) {
description = s;
}
public String getDescription() {
return description;
}
public void setPrice(Double d) {
price = d;
}
public Double getPrice() {
return price;
}
}