package example.dao; import example.model.Computer; import example.utils.DBUtils; import org.apache.commons.dbutils.QueryRunner; import org.apache.commons.dbutils.handlers.BeanListHandler; import java.util.List; public class CartDao { private final QueryRunner queryRunner = new QueryRunner(DBUtils.getDataSource()); // 加入购物车 public int addCart(Integer user_id, Integer product_id) throws Exception { String sql = "insert into cart(user_id, product_id) values(?,?)"; return queryRunner.update(sql, user_id, product_id); } // 移除购物车 public int deleteCart(Integer user_id, Integer product_id) throws Exception { String sql = "delete from cart where user_id=? and product_id=?"; return queryRunner.update(sql, product_id, user_id); } // 某用户的购物车 public List getCart(Integer user_id) throws Exception { String sql = "select\n" + "\tc2.*\n" + "from\n" + "\tcart c\n" + "left join computer c2 \n" + "on\n" + "\tc.product_id = c2.id\n" + "where\n" + "\tc.user_id = ?"; return queryRunner.query(sql,new BeanListHandler<>(Computer.class),user_id); } }