我有一个Component包含外键来自Component_category
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课堂上的外键实体上设置名称。我尝试了一些选项,但在不“访问”外键的情况下不知道如何解决查询。
component_table.component_cat_id
我碰巧发现答案隐藏在一个名为“ 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