订单
订单要写进数据库的
首先要确定两个实体类,一个是该订单的实体Order根据数据库的表单进行封装,外加一个List成员变量,用于存放订单的所有产品,订单的产品的实体OrderItem,利用表进行实体类的封装,当在购物车页面点击提交订单时,去寻找资源(servlet),所有订单内容均在session域中,在web层进行OrderITem与Oreder的封装,把封装好的Order传递给service,在service中开启事务,调用dao层的方法对两个表添加数据,两个表要同时成功,同时失败.
web
public void submitCart(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
Order order=new Order();
/*private String oid;
private Date orderTime;
private double total;
private int state;
private String address;
private String name;
private String telephone;
private User user;
private List<OrderItem> list=new ArrayList<>();*/
HttpSession session=request.getSession();
order.setOid(UUIDUtils.getUUID());
order.setOrderTime(new Date());
Cart cart=(Cart) session.getAttribute("cart");
order.setTotal(cart.getTotal());
order.setState(0);
order.setAddress(null);
order.setName(null);
order.setTelephone(null);
User user=(User) session.getAttribute("user");
order.setUser(user);
Map< String,CartItem> cartMap=cart.getCartMap();
for(Map.Entry<String, CartItem> entry:cartMap.entrySet()){
OrderItem item=new OrderItem();
/*private String itemid;
private int count;
private double subtotal;
private Product product;
private Order order;*/
item.setItemid(UUIDUtils.getUUID());
item.setCount(entry.getValue().getBuyNum());
item.setOrder(order);
item.setProduct(entry.getValue().getProduct());
item.setSubtotal(entry.getValue().getMinTotal());
order.getList().add(item);
}
ProductService service=new ProductService();
service.addData(order);
}
service
public class ProductService {
public void addData(Order order) {
try {
c3p0utils.startTransacation();
ProductDao dao=new ProductDao();
dao.addOrder(order);
dao.addOrderItem(order);
} catch (Exception e) {
try {
c3p0utils.rollback();
} catch (SQLException e1) {
e1.printStackTrace();
}
e.printStackTrace();
}finally{
try {
c3p0utils.commit();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}
dao
public class ProductDao {
QueryRunner qr=new QueryRunner();
Connection con=c3p0utils.getCurrentConnection();
public void addOrder(Order order) throws SQLException {
String sql="insert into orders values(?,?,?,?,?,?,?,?)";
qr.update(con,sql,order.getOid(),order.getOrderTime(),
order.getTotal(),order.getState(),order.getAddress(),
order.getName(),order.getTelephone(),order.getUser().getUid());
}
public void addOrderItem(Order order) throws SQLException {
List<OrderItem> list=order.getList();
String sql="insert into orderitem values (?,?,?,?,?)";
for(OrderItem item:list){
qr.update(con,sql,item.getItemid(),item.getCount(),
item.getSubtotal(),item.getProduct().getPid(),item.getOrder().getAddress());
}
}
}
当用到事务时,对事物的操作及对sql语句的操作都要用同一个Connection对象,因此就用到了ThreadLocal,在ThreadLocal中存入一个Connection对象,先判段ThreadLocal中有没有,如果没有在添加.service中不要出现Connection对象,所以对事物的操作写在工具类中,使用时类名.调用即可,QueryRunner中不放连接池,
在操作sql语句时放入从ThreadLacal中获取的连接.