/*!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 */;
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;
}
}
}
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;
}
}