gpt4 book ai didi

database - Android Room数据库: How to embed multiple entities

转载 作者:行者123 更新时间:2023-12-04 12:56:49 25 4
gpt4 key购买 nike

我正在为新项目使用空间,但是我在为如何干净地访问一对一值而苦苦挣扎
我有地址,所有者和站点的实体,所有者和站点都有一个关联的地址,并且每个站点都有一个所有者
是否可以干净地访问这些文件,例如site.owner.address.l1

我查看了@Relation,尽管它返回的列表不理想

实体

@Entity(tableName="addresses")
data class Address(
@PrimaryKey
@ColumnInfo(name="address_id")
val id: Int,

@ColumnInfo(name="address_l1")
val l1: String
)

@Entity(tablename="owners")
data class Owner(
@PrimaryKey
@ColumnInfo(name="owner_id")
val id: Int,

@ColumnInfo(name="owner_name")
val name: String
)

@Entity(tableName="sites")
data class Site(
@PrimaryKey
@ColumnInfo(name="site_id")
val id: Int,

@ColumnInfo(name="site_addressid")
val addressid: Int

@ColumnInfo(name="site_ownerid")
val ownerid: Int
)

道氏
@Query("SELECT * FROM sites")
fun getSites(): List<Site>

@Query("SELECT * FROM owners")
fun getOwners(): List<Owner>

@Query("SELECT * FROM addresses")
fun getAddresses(): List<Address>

@Query("SELECT * FROM sites JOIN address ON sites.site_addressid = address.address_id JOIN owners ON sites.site_ownerid = owners.owner_id JOIN address ON owners.owner_addressid = address.address_id WHERE sites.site_id = :siteid")
fun getSiteByIdWithDetails(siteid): Site

我只能看到多个POJO的方法来完成这项工作,例如
无效,但大致正确
data class OwnerAddress(
@Embedded
val owner: Owner,

@Embedded
val address: Address
)

data class SiteAddress(
@Embedded
val site: Site,

@Embedded
val owner: OwnerAddress,

@Embedded
val address: Address
}

并通过使用它
@Query("SELECT * FROM sites JOIN address ON sites.site_addressid = address.address_id JOIN owners ON sites.site_ownerid = owners.owner_id JOIN address ON owners.owner_addressid = address.address_id WHERE sites.site_id = :siteid")
fun getSiteByIdWithDetails(siteid): SiteAddress

最佳答案

您是否尝试过在实体之间建立关系? Android Documentation for Relationships

@Entity(tableName="addresses")
data class Address(
@PrimaryKey
@ColumnInfo(name="address_id")
val id: Int,

@ColumnInfo(name="address_l1")
val l1: String
)

@Entity(tablename="owners")
data class Owner(
@PrimaryKey
@ColumnInfo(name="owner_id")
val id: Int,

@ColumnInfo(name="owner_name")
val name: String

@ColumnInfo(name="owner_adress")
@Entity val adress: Address
)

@Entity(tableName="sites")
data class Site(
@PrimaryKey
@ColumnInfo(name="site_id")
val id: Int,

@ColumnInfo(name="site_owner")
@Embedded val owner: Owner

@ColumnInfo(name="site_address")
@Embedded val address: Address
)

因此,现在您的站点具有一个地址和一个所有者(具有其地址)。您的 sites表和 owners表都将包含“地址”列。

关于database - Android Room数据库: How to embed multiple entities,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51860810/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com