在文件、数据绑定、Room DB 中发现重复 class

Duplicate class found in file, Data Binding, Room DB

我遇到了一个非常烦人的错误。我正在实施房间数据库。当我在 DAO 中为另一个 table 编写插入查询时,class android 工作室生成与 android 数据绑定相关的编译错误 这是我的 DAO Class

@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();

}

这是我的关于实体 Class

@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 class

@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;
}

} build failed log

如果没有看到您遇到的实际错误,很难说清楚,但我猜您的问题是由于同一 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,所以我可能会坚持这一点。

来自official documentation

It is recommended to have multiple Dao classes in your codebase depending on the tables they touch.

为了使其正常工作,请记住将所有 DAO 包含在 Room 数据库的声明中!