我面临一个非常烦人的错误。我正在实施会议室DB。当我在DAO中为另一个表编写插入查询时,类android studio会生成与android数据绑定相关的编译错误 这是我的DAO课
@Dao
public interface MyCustomDAO {
@Insert(onConflict = OnConflictStrategy.REPLACE)
void insertShop(ShopModel shop);
//whenever i write this insert query, my android studio generate the stated error
// and when i remove it project buil successfully
@Insert(onConflict = OnConflictStrategy.REPLACE)
void insertAbout(AboutEntity about);
@Query("Select * From shops")
LiveData<List<ShopModel>> getShopsData();
}
这是我的关于实体类
@Entity(
tableName = "about",
foreignKeys = {@ForeignKey(entity = ShopModel.class,parentColumns = "shop_id",childColumns = "id")}
)
// i have implemented the shopModel class with a col namely, shop_id
public class AboutEntity {
@NonNull
@ColumnInfo(name = "id")
private String shopId;
@ColumnInfo
private String monToFriTiming;
@ColumnInfo
private String satTiming;
@ColumnInfo
private String sunTiming;
@ColumnInfo
private String description;
public AboutEntity(@NonNull String shopId, String monToFriTiming, String satTiming, String sunTiming, String description) {
this.shopId = shopId;
this.monToFriTiming = monToFriTiming;
this.satTiming = satTiming;
this.sunTiming = sunTiming;
this.description = description;
}
@NonNull
public String getShopId() {
return shopId;
}
// other fields getter Methods
}
这是ShopModel类
@Entity
public class ShopModel {
@NonNull
@PrimaryKey
@ColumnInfo(name = "shop_id")
private String id;
// some other fields and their implementation in the constructor and getter methods for them
public ShopModel(@NonNull String id) {
this.id = id;
}
@NonNull
public String getId() {
return id;
}
答案 0 :(得分:0)
在看不到实际错误的情况下很难分辨,但是我的猜测是您的问题是由于在同一DAO中针对不同实体具有多种插入方法所致。
代替这样做:
@Dao
public interface WrongDAO {
@Insert(onConflict = OnConflictStrategy.REPLACE)
void insertShop(ShopModel shop);
@Insert(onConflict = OnConflictStrategy.REPLACE)
void insertAbout(AboutEntity about);
@Query("Select * From shops")
LiveData<List<ShopModel>> getShopsData();
}
通常,您应该始终为每个实体创建一个不同的DAO ,以使代码更有条理:
@Dao
public interface ShopDAO {
@Insert(onConflict = OnConflictStrategy.REPLACE)
void insertShop(ShopModel shop);
@Query("Select * From shops")
LiveData<List<ShopModel>> getShopsData();
}
@Dao
public interface AboutDAO {
@Insert(onConflict = OnConflictStrategy.REPLACE)
void insertAbout(AboutEntity about);
}
我不确定在Room中是否必须执行此操作,但是到目前为止,我看到的所有示例每个实体都有一个DAO,所以我可能会坚持下去。
建议您的代码库中包含多个Dao类 取决于他们接触的桌子。
要使其正常工作,请记住在Room数据库的声明中包括所有DAO!