Android数据库GreenDAO3.2.2的使用(五,SQLiteConstraintException因为主键报错)

本文探讨了在使用GreenDao框架时,主键ID数据类型选择不当可能导致的问题。特别是当主键类型设置为long且未指定自增属性时,可能会遇到插入数据时ID重复的错误。文章提供了修改代码以避免该问题的方法。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

GreenDao第一篇文章提到主键ID数据类型有坑,下面先看一下一次log:android.database.sqlite.SQLiteConstraintException: UNIQUE constraint failed: USER._id (code 1555)


insert的时候id出现重复,但是设置主键了啊,为什么会重复呢?看代码:

@Entity
public class User {
    @Id
    private long id;
再进入Id看源码:

/**
 * Marks field is the primary key of the entity's table
 */
@Retention(RetentionPolicy.SOURCE)
@Target(ElementType.FIELD)
public @interface Id {
    /**
     * Specifies that id should be auto-incremented (works only for Long/long fields)
     * Autoincrement on SQLite introduces additional resources usage and usually can be avoided
     * @see <a href="https://www.sqlite.org/autoinc.html">SQLite documentation</a>
     */
    boolean autoincrement() default false;
}
好像也没有发现什么错啊,完后改为:

@Entity
public class User {
    @Id(autoincrement = true)
    private long id;
或者改为:

@Entity
public class User {
    @Id
    private Long id;
在insert的时候就不会报错了。

总结:在设置主键id为“long”的时候,加上(autoincrement=true),而使用“long”的包装类“Long”的时候,加上(autoincrement=true)或者不加都不会报错,具体什么原因导致的还没有弄清楚,欢迎指点。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值