使用GreenDao实现购物车功能

最近在做商城的项目,购物车的功能是核心,为了实现此功能,选用了GreenDao来实现数据的存储,当然在实际中,服务器和数据库之间数据的转换,才是完整的购物车功能。本篇文章只做GreenDao在购物车方面的使用介绍,关于GreenDao的配置,请参考https://github.com/greenrobot/greenDAO,下面附上效果图:




其实要做购物车,首先要明白购物车内部的产品关系,即店铺和产品的关系,很明显店铺和产品是一对多的关系,因此在设计数据库的时候就要使用GreenDao的一对多类型,下面附上具体代码:

1.商品表(需要注意的是,Generated内的hash值和变量的get/set方法是GreenDao自己生成的,切勿自己添加,否则,自己实践)

import org.greenrobot.greendao.annotation.Entity;
import org.greenrobot.greendao.annotation.Generated;
import org.greenrobot.greendao.annotation.Id;


@Entity
public class GoodsEntry {
    private int goodsOldMoney;
    private String goodsDes;
    private String goodsImage;
    private String goodsName;
    @Id
    private Long goodsId;
    private Long shopId;
    private int goodsBuyNum;
    private int goodsMoney;
    private String color;
    private String size;
    @Generated(hash = 414987192)
    public GoodsEntry() {
    }
    @Generated(hash = 857959235)
    public GoodsEntry(int goodsOldMoney, String goodsDes, String goodsImage, String goodsName, Long goodsId, Long shopId, int goodsBuyNum,
            int goodsMoney, String color, String size) {
        this.goodsOldMoney = goodsOldMoney;
        this.goodsDes = goodsDes;
        this.goodsImage = goodsImage;
        this.goodsName = goodsName;
        this.goodsId = goodsId;
        this.shopId = shopId;
        this.goodsBuyNum = goodsBuyNum;
        this.goodsMoney = goodsMoney;
        this.color = color;
        this.size = size;
    }
    public int getGoodsOldMoney() {
        return this.goodsOldMoney;
    }
    public void setGoodsOldMoney(int goodsOldMoney) {
        this.goodsOldMoney = goodsOldMoney;
    }
    public String getGoodsDes() {
        return this.goodsDes;
    }
    public void setGoodsDes(String goodsDes) {
        this.goodsDes = goodsDes;
    }
    public String getGoodsImage() {
        return this.goodsImage;
    }
    public void setGoodsImage(String goodsImage) {
        this.goodsImage = goodsImage;
    }
    public String getGoodsName() {
        return this.goodsName;
    }
    public void setGoodsName(String goodsName) {
        this.goodsName = goodsName;
    }
    public Long getGoodsId() {
        return this.goodsId;
    }
    public void setGoodsId(Long goodsId) {
        this.goodsId = goodsId;
    }
    public Long getShopId() {
        return this.shopId;
    }
    public void setShopId(Long shopId) {
        this.shopId = shopId;
    }
    public int getGoodsBuyNum() {
        return this.goodsBuyNum;
    }
    public void setGoodsBuyNum(int goodsBuyNum) {
        this.goodsBuyNum = goodsBuyNum;
    }
    public int getGoodsMoney() {
        return this.goodsMoney;
    }
    public void setGoodsMoney(int goodsMoney) {
        this.goodsMoney = goodsMoney;
    }
    public String getColor() {
        return this.color;
    }
    public void setColor(String color) {
        this.color = color;
    }
    public String getSize() {
        return this.size;
    }
    public void setSize(String size) {
        this.size = size;   
    }

2.店铺表(带有注释的和get/set方法都是GreenDao自己生成的,关键在于店铺ID属性,这是商品和店铺建立纽带的外键,GreenDao的 ToMany(referencedJoinProperty=“外键”))是一对多关系的注解

import org.greenrobot.greendao.DaoException;
import org.greenrobot.greendao.annotation.Entity;
import org.greenrobot.greendao.annotation.Generated;
import org.greenrobot.greendao.annotation.Id;
import org.greenrobot.greendao.annotation.ToMany;

import java.util.List;

@Entity
public class GoodsDetailEntry {
    @Id
    private Long shopId;
    private String shopName;
    @ToMany(referencedJoinProperty = "shopId")
    private List<GoodsEntry> list;
    /** Used to resolve relations */
    @Generated(hash = 2040040024)
    private transient DaoSession daoSession;
    /** Used for active entity operations. */
    @Generated(hash = 706725451)
    private transient GoodsDetailEntryDao myDao;
    @Generated(hash = 181135608)
    public GoodsDetailEntry(Long shopId, String shopName) {
        this.shopId = shopId;
        this.shopName = shopName;
    }
    @Generated(hash = 1925892336)
    public GoodsDetailEntry() {
    }
    public Long getShopId() {
        return this.shopId;
    }
    public void setShopId(Long shopId) {
        this.shopId = shopId;
    }
    public String getShopName() {
        return this.shopName;
    }
    public void setShopName(String shopName) {
        this.shopName = shopName;
    }
    /**
     * To-many relationship, resolved on first access (and after reset).
     * Changes to to-many relations are not persisted, make changes to the target entity.
     */
    @Generated(hash = 560962175)
    public List<GoodsEntry> getList() {
        if (list == null) {
            final DaoSession daoSession = this.daoSession;
            if (daoSession == null) {
                throw new DaoException("Entity is detached from DAO context");
            }
            GoodsEntryDao targetDao = daoSession.getGoodsEntryDao();
            List<GoodsEntry> listNew = targetDao
                    ._queryGoodsDetailEntry_List(shopId);
            synchronized (this) {
                if (list == null) {
                    list = listNew;
                }
            }
        }
        return list;
    }
    /** Resets a to-many relationship, making the next get call to query for a fresh result. */
    @Generated(hash = 589833612)
    public synchronized void resetList() {
        list = null;
    }
    /**
     * Convenient call for {@link org.greenrobot.greendao.AbstractDao#delete(Object)}.
     * Entity must attached to an entity context.
     */
    @Generated(hash = 128553479)
    public void delete() {
        if (myDao == null) {
            throw new DaoException("Entity is detached from DAO context");
        }
        myDao.delete(this);
    }
    /**
     * Convenient call for {@link org.greenrobot.greendao.AbstractDao#refresh(Object)}.
     * Entity must attached to an entity context.
     */
    @Generated(hash = 1942392019)
    public void refresh() {
        if (myDao == null) {
            throw new DaoException("Entity is detached from DAO context");
        }
        myDao.refresh(this);
    }
    /**
     * Convenient call for {@link org.greenrobot.greendao.AbstractDao#update(Object)}.
     * Entity must attached to an entity context.
     */
    @Generated(hash = 713229351)
    public void update() {
        if (myDao == null) {
            throw new DaoException("Entity is detached from DAO context");
        }
        myDao.update(this);
    }
    /** called by internal mechanisms, do not call yourself. */
    @Generated(hash = 260075940)
    public void __setDaoSession(DaoSession daoSession) {
        this.daoSession = daoSession;
        myDao = daoSession != null ? daoSession.getGoodsDetailEntryDao() : null;
    }
}

3.购物车实现(请参考https://github.com/cmazxiaoma/taobao,开源的购物车项目,本篇文章就是在此基础上进行修改)

a.商品添加

    GoodsDetailEntryDao goodsDetailEntryDao1 = BaseApplication.getInstances().getDaoSession().getGoodsDetailEntryDao();//获取商铺表
                List<GoodsDetailEntry> goodsDetailEntries = goodsDetailEntryDao1.loadAll();//获取所有的店铺列表
                GoodsEntryDao goodsEntryDao = BaseApplication.getInstances().getDaoSession().getGoodsEntryDao();//获取商品表
                GoodsEntry goodsEntry = new GoodsEntry();//创建商品对象
                goodsEntry.setGoodsName(bean.getGoodsName());//bean为作为传递的商品临时对象
                goodsEntry.setGoodsId(bean.getId());
                goodsEntry.setGoodsDes(bean.getGoodsDesc());
                goodsEntry.setGoodsBuyNum(1);
                goodsEntry.setShopId(bean.getShopId());
                goodsEntry.setGoodsMoney(bean.getPrice());
                goodsEntry.setGoodsOldMoney(bean.getOldPrice());
                goodsEntry.setGoodsImage(bean.getImageId());
                goodsEntry.setColor("蓝色");
                goodsEntry.setSize("40");
                GoodsDetailEntry goodsDetailEntry = new GoodsDetailEntry();//创建店铺对象
                if (goodsDetailEntries.size()==0){//店铺列表为0说明购物车为空,直接插入商品和店铺
                    GoodsDetailEntry detatilEntry = new GoodsDetailEntry();
                    detatilEntry.setShopId(bean.getShopId());
                    detatilEntry.setShopName(bean.getShopName());
                    goodsEntryDao.insert(goodsEntry);
                    goodsDetailEntryDao1.insert(detatilEntry);
                }else {
                    for (GoodsDetailEntry detailEntry:goodsDetailEntries) {
                        List<GoodsEntry> detailEntryList = detailEntry.getList();//获取当前店铺下的已加入购物车的所有商品
                        if (detailEntry.getShopId().equals(bean.getShopId())){//同一店铺下的处理
                            for (int i = 0; i <detailEntryList.size(); i++) {
                                GoodsEntry entry = detailEntryList.get(i);
                                if (entry.getGoodsId().equals(bean.getId())){//如果商品存在购物车,只需数量加1即可,更新商品表,更新店铺表
                                    goodsEntry.setGoodsBuyNum(entry.getGoodsBuyNum()+1);
                                    goodsEntryDao.update(goodsEntry);
                                    goodsDetailEntry.setShopName(bean.getShopName());
                                    goodsDetailEntry.setShopId(bean.getShopId());
                                    goodsDetailEntryDao1.update(goodsDetailEntry);

                                }else {//如果商品在购物车不存在,插入商品表,更新店铺表,此处使用捕获异常来终止循环,尝试break无效
                                    try {
                                        goodsEntryDao.insert(goodsEntry);
                                        goodsDetailEntry.setShopName(bean.getShopName());
                                        goodsDetailEntry.setShopId(bean.getShopId());
                                        goodsDetailEntryDao1.update(goodsDetailEntry);
                                    }catch (Exception e){
                                        e.printStackTrace();
                                    }
                                }
                            }
                        }else {//不同店铺下的处理,插入商品表,插入店铺表,此处同上使用捕获异常终止循环
                            try {
                                goodsEntryDao.insert(goodsEntry);
                                goodsDetailEntry.setShopName(bean.getShopName());
                                goodsDetailEntry.setShopId(bean.getShopId());
                                goodsDetailEntryDao1.insert(goodsDetailEntry);
                            }catch (Exception e){
                                e.printStackTrace();
                            }
                        }

                    }
                }

b.获取购物车详情

  /**
     * 模拟数据<br>
     * 遵循适配器的数据列表填充原则,组元素被放在一个list中,对应着组元素的下辖子元素被放在Map中
     * 其Key是组元素的Id
     */
    private void initData() {
        mcontext = this;
        groups = new ArrayList<StoreInfo>();
        childs = new HashMap<String, List<GoodsInfo>>();
        DaoSession daoSession =  BaseApplication.getInstances().getDaoSession();
        GoodsDetailEntryDao goodsDetailEntryDao = daoSession.getGoodsDetailEntryDao();
        List<GoodsDetailEntry> goodsDetailEntries = goodsDetailEntryDao.loadAll();
        for (int i = 0;i <goodsDetailEntries.size();i++) {
            GoodsDetailEntry detailEntry = goodsDetailEntries.get(i);
            groups.add(new StoreInfo(String.valueOf(detailEntry.getShopId()),detailEntry.getShopName()));
            List<GoodsInfo> goods = new ArrayList<>();
            List<GoodsEntry> goodsEntries = detailEntry.getList();
            for (int j = 0; j <goodsEntries.size() ; j++) {
                GoodsEntry entry = goodsEntries.get(j);
                goods.add(new GoodsInfo(String.valueOf(entry.getGoodsId()),entry.getGoodsName(),entry.getGoodsDes(),entry.getGoodsMoney(),entry.getGoodsOldMoney(),entry.getColor(),entry.getSize(),entry.getGoodsImage(),entry.getGoodsBuyNum()));
            }
            childs.put(groups.get(i).getId(), goods);
        }

    }
好了,核心代码都贴上了,大家赶紧去实现吧!!!!

猜你喜欢

转载自blog.csdn.net/hardWork_yulu/article/details/79355970