我正在学习如何在Android中使用Room。我有两个表:KeyWordsTable(标识,关键字)和CategoriesTable(标识,imagePath)。我想做这样的事情: 用户给一个关键字->检查它属于哪个类别->从CategoriesTable获取imagePath。
我有@Dao界面,并且做过类似的事情
@Query("SElECT image_path AS imagePath FROM CategoriesTable JOIN KeywordsTable ON idKeyWords = idCategories WHERE category_name = :categoryName LIMIT 1")
CategoriesTable findImagePathByKeyWordName(String categoryName);
这是正确的解决方案吗?我可以通过输入关键字来获取imagePath吗?
谢谢您的建议:)
CategoriesTable.class
@Entity
public class CategoriesTable {
@NonNull
@PrimaryKey(autoGenerate = true)
private int idCategories;
@ColumnInfo(name = "category_name")
private String categoryName;
@ColumnInfo(name = "image_path")
private String imagePath;
//getters and setters
KeywordsTable.class
@Entity
public class KeywordsTable {
@PrimaryKey(autoGenerate = true)
private int idKeyWords;
@ColumnInfo(name = "keywords_name")
private String keywordsName;
//getters and setters
答案 0 :(得分:1)
首先,必须在关系的many
端提供外键。此外,您应该在每个表的@Entity
批注中设置名称。
KeywordsTable.java
@Entity(tableName = "keywords",
foreignKeys = @ForeignKey(entity = CategoriesTable.class,
parentColumns = "idCategories",
childColumns = "categoryId",
onDelete = CASCADE))
public class KeywordsTable {
@PrimaryKey(autoGenerate = true)
private int idKeyWords;
@ColumnInfo(name = "keywords_name")
private String keywordsName;
private int categoryId;
//getters and setters
}
CategoriesTable.java
@Entity(tableName = "categories")
public class CategoriesTable {
@PrimaryKey(autoGenerate = true)
private int idCategories;
@ColumnInfo(name = "category_name")
private String categoryName;
@ColumnInfo(name = "image_path")
private String imagePath;
//getters and setters
}
dao接口中的方法应如下所示:
@Query("SELECT image_path FROM categories INNER JOIN keywords" +
"ON idCategories = categoryId WHERE keywords_name = :keyword LIMIT 1")
String findImagePathByKeyWordName(String keyword);