GreenDao java.lang.UnsupportedOperationException: Unsupported for entities with a non-null key

每次 找到一个bug  总会低呼一声  我**怎么会犯这么**的错误  

这个bug 是在GreenDao中遇到的 记录一下自己的马虎大意 

解决办法:

 如果 主键如果是数字类型,必须使用封装类型

例如:

​
    /**
     * 数据库id 自增
     */
    @Id(autoincrement = true)
    private Long dbid;

​

还原错误:

之前我的id  使用的是这样的  

 /**
     * 数据库id 自增
     */
    @Id(autoincrement = true)
    private long dbid;

当我使用了   自动生成的 save()方法后

    mUserBeanDao.save(userBean);

出现了  文章开头的错误

java.lang.UnsupportedOperationException: Unsupported for entities with a non-null key  

查看save()源码发现 其中使用了 haskey()方法  

save源码

 /**
     * "Saves" an entity to the database: depending on the existence of the key property, it will be inserted
     * (key is null) or updated (key is not null).
     * <p>
     * This is similar to {@link #insertOrReplace(Object)}, but may be more efficient, because if a key is present,
     * it does not have to query if that key already exists.
     */
    public void save(T entity) {
        if (hasKey(entity)) {
            update(entity);
        } else {
            insert(entity);
        }
    }

搜寻发现 该方法为 AbstractDao类的抽象方法

   /**
     * Returns true if the entity is not null, and has a non-null key, which is also != 0.
     * entity is null.
     */
    abstract protected boolean hasKey(T entity);

生成相应的 Dao类 都会继承 AbstractDao  类 

public class UserBeanDao extends AbstractDao<UserBean, Long> {

在类中 搜寻我们想看的方法  

    @Override
    public boolean hasKey(UserBean entity) {
        throw new UnsupportedOperationException("Unsupported for entities with a non-null key");
    }

发现 直接异常了   

检查 改正后 


    @Override
    public boolean hasKey(UserBean entity) {
        return entity.getDbid() != null;
    }

方法则不会出现异常  save方法 也可以正常使用 

 

总结 :仔细看文档  

你的每一个的赞  都是我坚持的理由

 

  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值