使用greenDAO遇到的问题

前一阵花时间学习了一下greenDAO的使用,这两天已经把项目中之前使用的sqlite数据库操作改用greenDAO,但是在改动的过程中还是出了一些问题,问题主要集中在主键上,下面整理了一下在改动过程中遇到的问题。

  • 调用AbstractDAO中update()时抛出RuntimeException

Cannot update entity without key - was it inserted before?

  • 抛出该异常的原因:在调用update()时传入的主键为 null
  • 该问题的应用环境:表中满足某条件的记录不重复,有则改之,无则’加冕’。
  • 解决问题的方法:查询表中满足条件的记录,取其id赋值给新记录。

部分代码块

  • 数据操作封装
public void cache(Cache cache) {
    String address = cache.getAccessAddress();
    QueryBuilder<Cache> builder = mCacheManager.queryBuilder().
    where(Properties.AccessAddress.eq(address));

    List<Cache> list = builder.list();
    if (null == list || list.isEmpty()) {
        // 未缓存
        mCacheManager.insert(cache);
    } else {
        // 新记录的id传进来为null
        Cache entity = list.get(0);
        cache.setId(entity.getId());
        mCacheManager.update(cache);
    }
}
posted @ 2015-12-25 17:34  祁连山  阅读(1124)  评论(0编辑  收藏  举报