每次 找到一个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方法 也可以正常使用
总结 :仔细看文档
你的每一个的赞 都是我坚持的理由