在Room中,如何在POJO中指定父实体关系?

时间:2019-05-30 15:38:43

标签: android kotlin android-room androidx

在Androidx Room中,如何检索POJO中的所有实体关系?

我具有以下数据库结构,其中A是B的父级,而B是C的父级:

@Entity(tableName="a")
class A(){
  @PrimaryKey
  var id: Long = 0L,

  var name: String = ""
}

@Entity(tableName= "b",
        foreignKeys = arrayOf(
            ForeignKey(
                entity = A::class,
                parentColumns = arrayOf("id"),
                childColumns = arrayOf("a_id"),
                onDelete = ForeignKey.CASCADE
                ))
)
class B() {
  @PrimaryKey(autoGenerate = true)
  var id: Long = 0L,

  @ColumnInfo(name="a_id")
  var aId: Long = 0L,

  var name: String = ""
)

@Entity(tableName= "c",
        foreignKeys = arrayOf(
            ForeignKey(
                entity = B::class,
                parentColumns = arrayOf("id"),
                childColumns = arrayOf("b_id"),
                onDelete = ForeignKey.CASCADE
                ))
)
data class C (
    @PrimaryKey(autoGenerate = true)
    var id: Long = 0L,

    @ColumnInfo(name ="b_id")
    var bId: Long = 0L,

    var name: String = ""
)

我想编写一个POJO,其中应包含B及其所有C和其父A:

class BAndAllCs {
   @Embedded
   var b: B? = null

   @Relation(parentColumn = "id",
             entityColumn = "b_id",
             entity= C::class)
   var c_all: List<C> = ArrayList()

   //how to retrieve parent A of B? 
}

因此,在BDao中,我可以添加以下内容:

@Transaction
@Query("SELECT * FROM B")
List<BAndAllCs> getAllB();

是否可以嵌入“ b”的父项“ a”?有没有一种方法可以习惯性地编码这种用法?有建议的最佳做法吗?

1 个答案:

答案 0 :(得分:0)

无需嵌入父A对象,只需使用Dao中的内部连接将相关字段从A放入POJO。

道:

@Transaction
@Query("SELECT B.*, A.name as a_name FROM B inner join A on b.a_id = a.id")
List<BAndAllCs> getAllB();

POJO:

class BAndAllCs {
   @Embedded
   var b: B? = null

   @ColumnInfo("a_name")
   var aName: String = ""

   @Relation(parentColumn = "id",
             entityColumn = "b_id",
             entity= C::class)
   var c_all: List<C> = ArrayList()
}