【问题标题】:Android Room - Usage of foreign key in queryAndroid Room - 在查询中使用外键
【发布时间】:2018-11-30 17:28:35
【问题描述】:

我有一个 Component,其中包含来自 Component_category 的外键

我的目的是按所选组件类别过滤组件列表。

两个类如下:


组件

@Entity(tableName = "component_table", foreignKeys = {
        @ForeignKey(
            entity = Rack.class,
            parentColumns = "rack_id",
            childColumns = "component_id",
            onDelete = ForeignKey.CASCADE,
            onUpdate = ForeignKey.CASCADE
        ),
        @ForeignKey(
            entity = ComponentCat.class,
            parentColumns = "component_cat_id",
            childColumns = "component_id",
            onDelete = ForeignKey.CASCADE,
            onUpdate = ForeignKey.CASCADE
        )
})

public class Component {

    @PrimaryKey(autoGenerate = true)
    @ColumnInfo(name = "component_id")
    public int componentID;

    @NonNull
    @ColumnInfo(name = "component_name")
    private String componentName;

    // .. omitted

组件类别

@Entity(tableName = "component_cat_table")

public class ComponentCat
{
    @PrimaryKey(autoGenerate = true)
    @ColumnInfo(name = "component_cat_id")
    public int componentCatID;

    @NonNull
    @ColumnInfo(name = "component_cat_name")
    private String componentCatName;

    // .. omitted

查询

我希望我的查询如下:

 @Query("SELECT * from component_table " +
        "INNER JOIN component_cat_table " +
        "WHERE component_table.component_cat_id == :categoryID ORDER BY component_name ASC")
        LiveData<List<Component>> getFilteredComponents(int categoryID);

但在编译时它告诉我它无法解析component_table.component_cat_id。我也无法在 Component 类的外键实体上设置名称。我尝试了几个选项,但我不知道如何在没有“访问”外键的情况下修复查询。

【问题讨论】:

    标签: android sql database android-sqlite android-room


    【解决方案1】:

    我碰巧在一个名为“android persistence”的示例项目中找到了答案。

    为了使用外键,还必须定义指定外键的列。列和外键数组之间的“链接”将自动建立。

       @Entity(foreignKeys = {
            @ForeignKey(entity = Book.class,
                    parentColumns = "id",
                    childColumns = "book_id"),
    
            @ForeignKey(entity = User.class,
                    parentColumns = "id",
                    childColumns = "user_id")})
    @TypeConverters(DateConverter.class)
    public class Loan {
        @PrimaryKey
        @NonNull
        public String id;
    
        public Date startTime;
    
        public Date endTime;
    
        @ColumnInfo(name="book_id")
        public String bookId;
    
        @ColumnInfo(name="user_id")
        public String userId;
    }
    

    以上示例来自以下链接。

    https://github.com/googlecodelabs/android-persistence/blob/master/app/src/main/java/com/example/android/persistence/codelab/db/Loan.java

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-10-26
      • 2012-12-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-09-24
      相关资源
      最近更新 更多