在Room永久性库中使用复合主键时,如何使主键自动递增? [英] How to make Primary key Auto increment while using Composite Primary keys in Room persistent library?

查看:909
本文介绍了在Room永久性库中使用复合主键时,如何使主键自动递增?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用Room持久性库.我需要在一个表中添加两个主键,并且其中一个主键应该是自动递增.我不知道确切的语法来实现这一目标.下面是我的Model类:

I am using Room persistent library. I have requirement to add two primary keys in one table and one of the primary key should be auto increment. I don't know exact syntax to achieve this. Below is my Model class:

@Entity(tableName = "newsPapers", primaryKeys = 
{"news_paper_id","news_paper_name"})
public class SelectNewsModel {

private int news_paper_id;

@ColumnInfo(name = "image_url")
private String imageUrl;

@ColumnInfo(name = "news_paper_name")
private String newsPaperName;
}

我想使"news_paper_id"自动递增.我该怎么做?

I want to make "news_paper_id" to be auto incremented. How can i make it?

推荐答案

我找到了解决此问题的另一种方法,因为据我的某些研究和开发经验,我们在复合主键中不能具有自动递增属性.所以我在这里使用了索引和唯一约束,因为到目前为止,Room还没有直接的UNIQUE约束.所以下面是我的工作代码:

I found another way around for this problem because as per my knowledge after some R&D, we can not have auto increment property in Composite Primary keys. So I used indices and unique constraint here because Room does not have direct UNIQUE constraint till now. So below is my working code:

@Entity(tableName = "newsPapers", indices = {@Index(value = 
       {"news_paper_name"}, unique = true)})
public class SelectNewsModel {

    @PrimaryKey(autoGenerate = true)
    private int news_paper_id;

    @ColumnInfo(name = "image_url")
    private String imageUrl;

    @ColumnInfo(name = "news_paper_name")
    private String newsPaperName;
}

这篇关于在Room永久性库中使用复合主键时,如何使主键自动递增?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆