接Java连接数据库#05#,对代码进行改进。
DAO层依赖关系草图
应用示例(只需3步!)
1、首先定义接口类:
package org.sample.shop.common.dao; import org.sample.shop.common.entity.Cart; import org.sample.shop.common.entity.Order; import java.util.List; public interface CartDAO { int addItem(Long uid, Long itemId); int removeItem(Long id); int removeAll(Long uid); // 清空购物车 List<Cart> listByUid(Long uid); Order getPreOrder(Long uid); }
2、然后书写相应的SQL以及返回类型(id的默认格式是“文件名_方法名”):
<sql id="cart_addItem"> INSERT INTO cart(user_id, item_id) VALUES (?, ?) </sql> <sql id="cart_removeAll"> DELETE FROM cart WHERE user_id=? </sql> <sql id="cart_removeItem"> DELETE FROM cart WHERE id=? </sql> <sql id="cart_getByUid" type="org.sample.shop.common.entity.Cart"> SELECT id, user_id AS userId, item_id AS itemId FROM cart WHERE user_id=? </sql> <sql id="cart_getPreOrder" type="org.sample.shop.common.entity.OrderDetail"> SELECT cart.id, item_id AS itemId, item.user_id AS userId, price FROM cart LEFT JOIN item ON cart.item_id = item.id WHERE cart.user_id=? </sql> <sql id="cart_getSum" type="java.lang.Number"> SELECT SUM(price) AS sum FROM cart LEFT JOIN item ON cart.item_id = item.id WHERE cart.user_id=? </sql>
3、最后,通过QueryRunnerProxy执行SQL并拿到所需对象。
package org.sample.shop.common.dao.impl; import org.sample.shop.common.dao.CartDAO; import org.sample.shop.common.db.QueryRunnerProxy; import org.sample.shop.common.entity.Cart; import org.sample.shop.common.entity.Order; import org.sample.shop.common.entity.OrderDetail; import java.util.List; import java.util.Map; public class CartDAOImpl implements CartDAO { @Override public int addItem(Long uid, Long itemId) { return QueryRunnerProxy.update("cart_addItem", uid, itemId); } @Override public int removeItem(Long id) { return QueryRunnerProxy.update("cart_removeItem", id); } @Override public int removeAll(Long uid) { return QueryRunnerProxy.update("cart_removeAll", uid); } @Override public List<Cart> listByUid(Long uid) { return QueryRunnerProxy.query("cart_getByUid", uid); } @Override public Order getPreOrder(Long uid) { Order order = new Order(); order.setUserId(uid); // 设置买家id // 1. 查总价 List<Map> mapList = QueryRunnerProxy.query("cart_getSum", uid); Double total = Double.parseDouble(mapList.get(0).get("sum").toString()); order.setTotal(total); // 2. 查对应的物品清单 List<OrderDetail> details = QueryRunnerProxy.query("cart_getPreOrder", uid); order.setDetails(details); return order; } }
具体实现代码参考github:https://github.com/xkfx/simple-shop
不过还有一些线程安全方面的隐患待解决。。。。。。。。。。。。。