一、主要功能
二、核心学习知识点
主要接口:
1.购物车List列表:/cart/list.do 2.购物车添加商品:/cart/add.do 3.更新购物车某个产品数量:/cart/update.do 4.移除购物车某个产品:/cart/delete_product.do 5.购物车选中某个商品:/cart/select.do 6.购物车取消选中某个商品:/cart/un_select.do 7.查询在购物车里的产品数量:/cart/get_cart_product_count.do 8.购物车全选:/cart/select_all.do 9.购物车取消全选:/cart/un_select_all.do
三、数据表设计
四、DAO
package com.mmall.dao; import com.mmall.pojo.Cart; import org.apache.ibatis.annotations.Param; import java.util.List; public interface CartMapper { int deleteByPrimaryKey(Integer id); int insert(Cart record); int insertSelective(Cart record); Cart selectByPrimaryKey(Integer id); int updateByPrimaryKeySelective(Cart record); int updateByPrimaryKey(Cart record); Cart selectCartByUserIdAndProductId(@Param("userId") Integer userId, @Param("productId") Integer productId); List<Cart> selectCartByUserId(Integer userId); int isAllChecked(Integer userId); int deleteByUserIdProductIds(@Param("userId") Integer userId, @Param("productIds") List<String> productIds); int checkedOrUncheckedAllProduct(@Param("userId") Integer userId, @Param("checked") Integer checked); int checkedOrUncheckedProduct(@Param("userId") Integer userId, @Param("checked") Integer checked, @Param("productId") Integer productId); int selectCartProductCount(int userId); }
mappers:
<?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd" > <mapper namespace="com.mmall.dao.CartMapper" > <resultMap id="BaseResultMap" type="com.mmall.pojo.Cart" > <constructor > <idArg column="id" jdbcType="INTEGER" javaType="java.lang.Integer" /> <arg column="user_id" jdbcType="INTEGER" javaType="java.lang.Integer" /> <arg column="product_id" jdbcType="INTEGER" javaType="java.lang.Integer" /> <arg column="quantity" jdbcType="INTEGER" javaType="java.lang.Integer" /> <arg column="checked" jdbcType="INTEGER" javaType="java.lang.Integer" /> <arg column="create_time" jdbcType="TIMESTAMP" javaType="java.util.Date" /> <arg column="update_time" jdbcType="TIMESTAMP" javaType="java.util.Date" /> </constructor> </resultMap> <sql id="Base_Column_List" > id, user_id, product_id, quantity, checked, create_time, update_time </sql> <select id="selectByPrimaryKey" resultMap="BaseResultMap" parameterType="java.lang.Integer" > select <include refid="Base_Column_List" /> from mmall_cart where id = #{id,jdbcType=INTEGER} </select> <delete id="deleteByPrimaryKey" parameterType="java.lang.Integer" > delete from mmall_cart where id = #{id,jdbcType=INTEGER} </delete> <insert id="insert" parameterType="com.mmall.pojo.Cart" > insert into mmall_cart (id, user_id, product_id, quantity, checked, create_time, update_time) values (#{id,jdbcType=INTEGER}, #{userId,jdbcType=INTEGER}, #{productId,jdbcType=INTEGER}, #{quantity,jdbcType=INTEGER}, #{checked,jdbcType=INTEGER}, now(), now()) </insert> <insert id="insertSelective" parameterType="com.mmall.pojo.Cart" > insert into mmall_cart <trim prefix="(" suffix=")" suffixOverrides="," > <if test="id != null" > id, </if> <if test="userId != null" > user_id, </if> <if test="productId != null" > product_id, </if> <if test="quantity != null" > quantity, </if> <if test="checked != null" > checked, </if> <if test="createTime != null" > create_time, </if> <if test="updateTime != null" > update_time, </if> </trim> <trim prefix="values (" suffix=")" suffixOverrides="," > <if test="id != null" > #{id,jdbcType=INTEGER}, </if> <if test="userId != null" > #{userId,jdbcType=INTEGER}, </if> <if test="productId != null" > #{productId,jdbcType=INTEGER}, </if> <if test="quantity != null" > #{quantity,jdbcType=INTEGER}, </if> <if test="checked != null" > #{checked,jdbcType=INTEGER}, </if> <if test="createTime != null" > now(), </if> <if test="updateTime != null" > now(), </if> </trim> </insert> <update id="updateByPrimaryKeySelective" parameterType="com.mmall.pojo.Cart" > update mmall_cart <set > <if test="userId != null" > user_id = #{userId,jdbcType=INTEGER}, </if> <if test="productId != null" > product_id = #{productId,jdbcType=INTEGER}, </if> <if test="quantity != null" > quantity = #{quantity,jdbcType=INTEGER}, </if> <if test="checked != null" > checked = #{checked,jdbcType=INTEGER}, </if> <if test="createTime != null" > create_time = #{createTime,jdbcType=TIMESTAMP}, </if> <if test="updateTime != null" > update_time = now(), </if> </set> where id = #{id,jdbcType=INTEGER} </update> <update id="updateByPrimaryKey" parameterType="com.mmall.pojo.Cart" > update mmall_cart set user_id = #{userId,jdbcType=INTEGER}, product_id = #{productId,jdbcType=INTEGER}, quantity = #{quantity,jdbcType=INTEGER}, checked = #{checked,jdbcType=INTEGER}, create_time = #{createTime,jdbcType=TIMESTAMP}, update_time = now() where id = #{id,jdbcType=INTEGER} </update> <select id="selectCartByUserIdAndProductId" resultMap="BaseResultMap" parameterType="map"> SELECT <include refid="Base_Column_List"/> FROM mmall_cart WHERE user_id = #{userId} AND product_id = #{productId} </select> <select id="selectCartByUserId" parameterType="int" resultMap="BaseResultMap"> SELECT <include refid="Base_Column_List"/> FROM mmall_cart WHERE user_id = #{userId} </select> <select id="isAllChecked" parameterType="int" resultType="int"> SELECT COUNT(1) FROM mmall_cart WHERE user_id = #{userId} AND checked = 0 </select> <delete id="deleteByUserIdProductIds" parameterType="map"> DELETE FROM mmall_cart WHERE user_id = #{userId} <if test="productIds != null"> AND product_id in <foreach collection="productIds" open="(" separator="," close=")" index="index" item="item"> #{item} </foreach> </if> </delete> <update id="checkedOrUncheckedAllProduct" parameterType="map"> UPDATE mmall_cart SET checked = #{checked},update_time = now() where user_id = #{userId} </update> <update id="checkedOrUncheckedProduct" parameterType="map"> UPDATE mmall_cart SET checked = #{checked},update_time = now() where user_id = #{userId} AND product_id = #{productId} </update> <select id="selectCartProductCount" parameterType="int" resultType="int"> select IFNULL(sum(quantity),0) as count from mmall_cart where user_id = #{userId} and </select> </mapper>
五、Service
package com.mmall.service; import com.mmall.common.ServerResponse; import com.mmall.vo.CartVo; /** * @author GenshenWang.nomico * @date 2018/4/15. */ public interface ICartService { ServerResponse<CartVo> addCart(Integer userId, Integer productId, Integer count); ServerResponse<CartVo> updateCart(Integer userId, Integer productId, Integer count); ServerResponse<CartVo> deleteProduct(Integer userId,String productIds); ServerResponse<CartVo> list(Integer userId); ServerResponse<CartVo> selectOrUnSelectAll(Integer userId, Integer checked); ServerResponse<CartVo> selectOrUnSelectProduct(Integer userId, Integer checked, Integer productId); ServerResponse<Integer> getCartProductCount(Integer userId); }
Impl:
package com.mmall.service.impl; import com.google.common.base.Splitter; import com.google.common.collect.Lists; import com.mmall.common.Const; import com.mmall.common.ResponseCode; import com.mmall.common.ServerResponse; import com.mmall.dao.CartMapper; import com.mmall.dao.ProductMapper; import com.mmall.pojo.Cart; import com.mmall.pojo.Product; import com.mmall.service.ICartService; import com.mmall.util.BigDecimalUtil; import com.mmall.util.PropertiesUtil; import com.mmall.vo.CartProductVo; import com.mmall.vo.CartVo; import org.apache.commons.collections.CollectionUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import java.math.BigDecimal; import java.util.List; /** * @author GenshenWang.nomico * @date 2018/4/15. */ @Service("iCartService") public class CartServiceImpl implements ICartService { @Autowired private CartMapper cartMapper; @Autowired private ProductMapper productMapper; @Override public ServerResponse<CartVo> addCart(Integer userId, Integer productId, Integer count){ if (productId == null || count == null){ return ServerResponse.createByErrorCodeMsg(ResponseCode.ILLEGAL_ARGUMENT.getCode(), ResponseCode.ILLEGAL_ARGUMENT.getDesc()); } Cart cart = cartMapper.selectCartByUserIdAndProductId(userId, productId); if (cart == null){ //新增 Cart cart1 = new Cart(); //CHECKED==1,选中 cart1.setChecked(Const.Cart.CHECKED); cart1.setQuantity(count); cart1.setUserId(userId); cart1.setProductId(productId); cartMapper.insert(cart1); }else { //更新 count = cart.getQuantity() + count; cart.setQuantity(count); cartMapper.updateByPrimaryKeySelective(cart); } CartVo cartVo = getCartVoLimit(userId); return ServerResponse.createBySuccess(cartVo); } @Override public ServerResponse<CartVo> updateCart(Integer userId, Integer productId, Integer count){ if (productId == null || count == null){ return ServerResponse.createByErrorCodeMsg(ResponseCode.ILLEGAL_ARGUMENT.getCode(), ResponseCode.ILLEGAL_ARGUMENT.getDesc()); } Cart cart = cartMapper.selectCartByUserIdAndProductId(userId, productId); if (cart != null){ cart.setQuantity(count); } cartMapper.updateByPrimaryKey(cart); CartVo cartVo = getCartVoLimit(userId); return ServerResponse.createBySuccess(cartVo); } @Override public ServerResponse<CartVo> deleteProduct(Integer userId, String productIds){ List<String> productIdList = Splitter.on(",").splitToList(productIds); if (CollectionUtils.isEmpty(productIdList)){ return ServerResponse.createByErrorCodeMsg(ResponseCode.ILLEGAL_ARGUMENT.getCode(), ResponseCode.ILLEGAL_ARGUMENT.getDesc()); } cartMapper.deleteByUserIdProductIds(userId, productIdList); CartVo cartVo = getCartVoLimit(userId); return ServerResponse.createBySuccess(cartVo); } @Override public ServerResponse<CartVo> list(Integer userId){ CartVo cartVo = getCartVoLimit(userId); return ServerResponse.createBySuccess(cartVo); } @Override public ServerResponse<CartVo> selectOrUnSelectAll(Integer userId, Integer checked){ cartMapper.checkedOrUncheckedAllProduct(userId, checked); return this.list(userId); } @Override public ServerResponse<CartVo> selectOrUnSelectProduct(Integer userId, Integer checked, Integer productId){ cartMapper.checkedOrUncheckedProduct(userId, checked, productId); return this.list(userId); } @Override public ServerResponse<Integer> getCartProductCount(Integer userId){ if(userId == null){ return ServerResponse.createBySuccess(0); } int count = cartMapper.selectCartProductCount(userId); return ServerResponse.createBySuccess(count); } //判断库存并返回处理后的结果 private CartVo getCartVoLimit(Integer userId){ CartVo cartVo = new CartVo(); List<Cart> cartList = cartMapper.selectCartByUserId(userId); //用来装配CartProductVo List<CartProductVo> cartProductVoList = Lists.newArrayList(); //购物车总价 BigDecimal cartTotalPrice = new BigDecimal("0"); if (CollectionUtils.isNotEmpty(cartList)){ //遍历每一个购物车,计算购物车中的每个产品数量。总价,库存等,用CartProductVo封装 for (Cart cartItem : cartList){ CartProductVo cartProductVo = new CartProductVo(); cartProductVo.setUserId(userId); cartProductVo.setId(cartItem.getId()); cartProductVo.setProductId(cartItem.getProductId()); //cartProductVo.setQuantity(); //cartProductVo.setProductTotalPrice(); Product product = productMapper.selectByPrimaryKey(cartItem.getProductId()); if (product != null){ cartProductVo.setProductMainImage(product.getMainImage()); cartProductVo.setProductSubtitle(product.getSubtitle()); cartProductVo.setProductName(product.getName()); cartProductVo.setProductPrice(product.getPrice()); cartProductVo.setProductStatus(product.getStatus()); cartProductVo.setProductStock(product.getStock()); //判断库存 int buyLimitCount = 0; if (product.getStock() >= cartItem.getQuantity()){ //库存充足 buyLimitCount = cartItem.getQuantity(); cartProductVo.setLimitQuantity(Const.Cart.LIMIT_NUM_SUCCESS); }else { //库存不足 buyLimitCount = product.getStock(); cartProductVo.setLimitQuantity(Const.Cart.LIMIT_NUM_FAIL); //购物车更新库存 Cart updateCart = new Cart(); updateCart.setId(cartItem.getId()); updateCart.setQuantity(buyLimitCount); cartMapper.updateByPrimaryKeySelective(updateCart); } cartProductVo.setQuantity(buyLimitCount); //总价=产品价格*购物车该产品数量 cartProductVo.setProductTotalPrice(BigDecimalUtil.mul(product.getPrice().doubleValue(), cartProductVo.getQuantity())); cartProductVo.setProductChecked(cartItem.getChecked()); } if (cartItem.getChecked() == Const.Cart.CHECKED){ //如果已经勾选,增加到整个的购物车总价中 cartTotalPrice = BigDecimalUtil.add(cartTotalPrice.doubleValue(), cartProductVo.getProductTotalPrice().doubleValue()); } cartProductVoList.add(cartProductVo); } } cartVo.setCartTotalPrice(cartTotalPrice); cartVo.setCartProductVoList(cartProductVoList); cartVo.setImageHost(PropertiesUtil.getProperty("ftp.server.http.prefix")); cartVo.setAllChecked(this.isAllChecked(userId)); return cartVo; } private boolean isAllChecked(Integer userId){ if (userId == null){ return false; } return cartMapper.isAllChecked(userId) == 0; } }
六、Controller
package com.mmall.controller.portal; import com.mmall.common.Const; import com.mmall.common.ResponseCode; import com.mmall.common.ServerResponse; import com.mmall.pojo.User; import com.mmall.service.ICartService; import com.mmall.vo.CartVo; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.ResponseBody; import javax.servlet.http.HttpSession; /** * @author GenshenWang.nomico * @date 2018/4/15. */ @Controller @RequestMapping(value = "/cart") public class CartController { @Autowired ICartService iCartService; /** * 购物车中添加商品 * @param session * @param productId * @param count * @return */ @RequestMapping(value = "/add.do", method = RequestMethod.POST) @ResponseBody public ServerResponse<CartVo> addCart(HttpSession session, Integer productId, Integer count){ User user = (User) session.getAttribute(Const.CURRENT_USER); if (user == null){ return ServerResponse.createByErrorCodeMsg(ResponseCode.NEED_LOGIN.getCode(), "未登录,请先登录"); } return iCartService.addCart(user.getId(), productId, count); } /** * 更新购物车中某个商品 * @param session * @param productId * @param count * @return */ @RequestMapping(value = "/update.do", method = RequestMethod.POST) @ResponseBody public ServerResponse<CartVo> updateCart(HttpSession session, Integer productId, Integer count){ User user = (User) session.getAttribute(Const.CURRENT_USER); if (user == null){ return ServerResponse.createByErrorCodeMsg(ResponseCode.NEED_LOGIN.getCode(), "未登录,请先登录"); } return iCartService.updateCart(user.getId(), productId, count); } /** * 移除购物车某个产品 * @param session * @param productIds * @return */ @RequestMapping(value = "/delete_product.do",method = RequestMethod.POST) @ResponseBody public ServerResponse<CartVo> deleteProduct(HttpSession session, String productIds){ User user = (User) session.getAttribute(Const.CURRENT_USER); if (user == null){ return ServerResponse.createByErrorCodeMsg(ResponseCode.NEED_LOGIN.getCode(), "未登录,请先登录"); } return iCartService.deleteProduct(user.getId(), productIds); } /** * 购物车List列表 * @param session * @return */ @RequestMapping(value = "/list.do", method = RequestMethod.POST) @ResponseBody public ServerResponse<CartVo> list(HttpSession session){ User user = (User) session.getAttribute(Const.CURRENT_USER); if (user == null){ return ServerResponse.createByErrorCodeMsg(ResponseCode.NEED_LOGIN.getCode(), "未登录,请先登录"); } return iCartService.list(user.getId()); } //全选 @RequestMapping(value = "/select_all.do", method = RequestMethod.POST) @ResponseBody public ServerResponse selectAll(HttpSession session){ User user = (User) session.getAttribute(Const.CURRENT_USER); if (user == null){ return ServerResponse.createByErrorCodeMsg(ResponseCode.NEED_LOGIN.getCode(), "未登录,请先登录"); } return iCartService.selectOrUnSelectAll(user.getId(), Const.Cart.CHECKED); } //取消全选 @RequestMapping(value = "/un_select_all.do", method = RequestMethod.POST) @ResponseBody public ServerResponse unSelectAll(HttpSession session){ User user = (User) session.getAttribute(Const.CURRENT_USER); if (user == null){ return ServerResponse.createByErrorCodeMsg(ResponseCode.NEED_LOGIN.getCode(), "未登录,请先登录"); } return iCartService.selectOrUnSelectAll(user.getId(), Const.Cart.UN_CHECKED); } //单个商品选中 @RequestMapping(value = "/select.do", method = RequestMethod.POST) @ResponseBody public ServerResponse selectProduct(HttpSession session, Integer productId){ User user = (User) session.getAttribute(Const.CURRENT_USER); if (user == null){ return ServerResponse.createByErrorCodeMsg(ResponseCode.NEED_LOGIN.getCode(), "未登录,请先登录"); } return iCartService.selectOrUnSelectProduct(user.getId(), Const.Cart.CHECKED, productId); } //取消单个商品选中 @RequestMapping(value = "/un_select.do", method = RequestMethod.POST) @ResponseBody public ServerResponse unSelectProduct(HttpSession session, Integer productId){ User user = (User) session.getAttribute(Const.CURRENT_USER); if (user == null){ return ServerResponse.createByErrorCodeMsg(ResponseCode.NEED_LOGIN.getCode(), "未登录,请先登录"); } return iCartService.selectOrUnSelectProduct(user.getId(), Const.Cart.UN_CHECKED, productId); } //查询购物车商品数量 @RequestMapping(value = "/get_cart_product_count.do", method = RequestMethod.POST) @ResponseBody public ServerResponse getCartProductCount(HttpSession session){ User user = (User) session.getAttribute(Const.CURRENT_USER); if (user == null){ return ServerResponse.createBySuccess(0); } return iCartService.getCartProductCount(user.getId()); } }
七、POJO与VO
Cart.java:
package com.mmall.pojo; import java.util.Date; public class Cart { private Integer id; private Integer userId; private Integer productId; private Integer quantity; private Integer checked; private Date createTime; private Date updateTime; public Cart(Integer id, Integer userId, Integer productId, Integer quantity, Integer checked, Date createTime, Date updateTime) { this.id = id; this.userId = userId; this.productId = productId; this.quantity = quantity; this.checked = checked; this.createTime = createTime; this.updateTime = updateTime; } public Cart() { super(); } public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public Integer getUserId() { return userId; } public void setUserId(Integer userId) { this.userId = userId; } public Integer getProductId() { return productId; } public void setProductId(Integer productId) { this.productId = productId; } public Integer getQuantity() { return quantity; } public void setQuantity(Integer quantity) { this.quantity = quantity; } public Integer getChecked() { return checked; } public void setChecked(Integer checked) { this.checked = checked; } public Date getCreateTime() { return createTime; } public void setCreateTime(Date createTime) { this.createTime = createTime; } public Date getUpdateTime() { return updateTime; } public void setUpdateTime(Date updateTime) { this.updateTime = updateTime; } }
CartProductVo.java:
package com.mmall.vo; import java.math.BigDecimal; /** * @author GenshenWang.nomico * @date 2018/4/15. */ public class CartProductVo { //结合了产品和购物车的一个抽象对象 private Integer id; private Integer userId; private Integer productId; private Integer quantity;//购物车中此商品的数量 private String productName; private String productSubtitle; private String productMainImage; private BigDecimal productPrice; private Integer productStatus; private BigDecimal productTotalPrice; private Integer productStock; private Integer productChecked;//此商品是否勾选 private String limitQuantity;//限制数量的一个返回结果 public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public Integer getUserId() { return userId; } public void setUserId(Integer userId) { this.userId = userId; } public Integer getProductId() { return productId; } public void setProductId(Integer productId) { this.productId = productId; } public Integer getQuantity() { return quantity; } public void setQuantity(Integer quantity) { this.quantity = quantity; } public String getProductName() { return productName; } public void setProductName(String productName) { this.productName = productName; } public String getProductSubtitle() { return productSubtitle; } public void setProductSubtitle(String productSubtitle) { this.productSubtitle = productSubtitle; } public String getProductMainImage() { return productMainImage; } public void setProductMainImage(String productMainImage) { this.productMainImage = productMainImage; } public BigDecimal getProductPrice() { return productPrice; } public void setProductPrice(BigDecimal productPrice) { this.productPrice = productPrice; } public Integer getProductStatus() { return productStatus; } public void setProductStatus(Integer productStatus) { this.productStatus = productStatus; } public BigDecimal getProductTotalPrice() { return productTotalPrice; } public void setProductTotalPrice(BigDecimal productTotalPrice) { this.productTotalPrice = productTotalPrice; } public Integer getProductStock() { return productStock; } public void setProductStock(Integer productStock) { this.productStock = productStock; } public Integer getProductChecked() { return productChecked; } public void setProductChecked(Integer productChecked) { this.productChecked = productChecked; } public String getLimitQuantity() { return limitQuantity; } public void setLimitQuantity(String limitQuantity) { this.limitQuantity = limitQuantity; } }
CartVo.java:
package com.mmall.vo; import java.math.BigDecimal; import java.util.List; /** * @author GenshenWang.nomico * @date 2018/4/15. */ public class CartVo { private List<CartProductVo> cartProductVoList; private BigDecimal cartTotalPrice; private Boolean allChecked;//是否已经都勾选 private String imageHost; public List<CartProductVo> getCartProductVoList() { return cartProductVoList; } public void setCartProductVoList(List<CartProductVo> cartProductVoList) { this.cartProductVoList = cartProductVoList; } public BigDecimal getCartTotalPrice() { return cartTotalPrice; } public void setCartTotalPrice(BigDecimal cartTotalPrice) { this.cartTotalPrice = cartTotalPrice; } public Boolean getAllChecked() { return allChecked; } public void setAllChecked(Boolean allChecked) { this.allChecked = allChecked; } public String getImageHost() { return imageHost; } public void setImageHost(String imageHost) { this.imageHost = imageHost; } }
八、Const
package com.mmall.common; import com.google.common.collect.Sets; import java.util.Set; /** * @author GenshenWang.nomico * @date 2018/4/5. */ public class Const { public static final String CURRENT_USER = "currentUser"; public static final String EMAIL = "email"; public static final String USERNAME = "username"; public interface Role{ int ROLE_CUSTOMER = 0; //普通用户 int ROLE_ADMIN = 1;//管理员 } public enum ProductStatusEnum { ON_SALE(1, "在售"); private int code; private String desc; ProductStatusEnum(int code, String desc){ this.code = code; this.desc = desc; } public int getCode() { return code; } public String getDesc() { return desc; } } public interface ProductListOrderBy{ //Set查询效率为O(1), List为O(n) Set<String> PRICE_ASC_DESC = Sets.newHashSet("price_desc","price_asc"); } public interface Cart{ int CHECKED = 1;//即购物车选中状态 int UN_CHECKED = 0;//即购物车未选中状态 String LIMIT_NUM_FAIL = "LIMIT_NUM_FAIL"; String LIMIT_NUM_SUCCESS = "LIMIT_NUM_SUCCESS"; } }
九、Util:
package com.mmall.util; import java.math.BigDecimal; /** * @author GenshenWang.nomico * @date 2018/4/17. */ public class BigDecimalUtil { private BigDecimalUtil(){ } public static BigDecimal add(double v1, double v2){ BigDecimal b1 = new BigDecimal(Double.toString(v1)); BigDecimal b2 = new BigDecimal(Double.toString(v2)); return b1.add(b2); } public static BigDecimal sub(double v1, double v2){ BigDecimal b1 = new BigDecimal(Double.toString(v1)); BigDecimal b2 = new BigDecimal(Double.toString(v2)); return b1.subtract(b2); } public static BigDecimal mul(double v1, double v2){ BigDecimal b1 = new BigDecimal(Double.toString(v1)); BigDecimal b2 = new BigDecimal(Double.toString(v2)); return b1.multiply(b2); } public static BigDecimal div(double v1, double v2){ BigDecimal b1 = new BigDecimal(Double.toString(v1)); BigDecimal b2 = new BigDecimal(Double.toString(v2)); //保留两位小数,四舍五入 return b1.divide(b2, 2, BigDecimal.ROUND_HALF_UP); } }