oducts (id, description, price) values(1, ''Lamp'', 5.78);
INSERT INTO products (id, description, price) values(2, ''Table'', 75.29);
INSERT INTO products (id, description, price) values(3, ''Chair'', 22.81);
这样就会在JBuilder_Home/bin目录下创建一个目录db,存放了数据库test的数据
22. 创建JDBC DAO (Data Access Object)实现
springapp/src/db/ProductManagerDao.java
package db;
import bus.Product;
import java.util.List;
public interface ProductManagerDao {
public List getProductList();
public void increasePrice(Product prod, int pct);
}
springapp/src/db/ProductManagerDaoJdbc.java
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;
}
}
}
利用JBuilder 2005开发Spring实例(7)
时间:2010-12-04
springapp/src/bus/Product.java
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 setPr
|