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)或者不加都不会报错,具体什么原因导致的还没有弄清楚,欢迎指点。