@Embedded 注解可用于组合类中的实体。
例如,使用问题中的实体,那么 ListItem 类的替代方案可能是:-
class UserOfficePlacesCombined() {
@Embedded(prefix = "user")
var user: User? = null
@Embedded(prefix = "office")
var office: Office? = null
@Embedded(prefix = "places")
var places: Places? = null
}
- 前缀已用于避免列名歧义,简而言之,所有列都将以相应表的名称作为前缀(请参阅下面的 Dao 查询)
然后您可以使用 Dao 查询提取 UserOfficePlacesCombined,例如:-
@Query("SELECT user.id AS userid, user.name AS username, " +
"office.id AS officeid, office.address AS officeaddress, " +
"places.id AS placesid, places.name AS placesname " +
"FROM User JOIN Office ON User.id = Office.id JOIN Places ON User.id = Places.id")
fun getAllUserOfficePlacesCombined(): UserOfficePlacesCombined
- 为避免歧义,所有列都已使用 AS 关键字重命名
- 如果表之间的关系问题没有指示,则查询将根据表的 id 列连接表。
- 这不太可能在应用程序中使用,但由于缺乏信息和方便起见,已经这样做了。
把这个作为一个例子,做一些假设,然后考虑下面的演示:-
val userOfficePlacesDoa = db.userOfficePlacesDao()
val user1 = User(1,"USER1")
val office1 = Office(1,"Office1")
val places1 = Places(1,"Place1")
userOfficePlacesDoa.insertUser(user1)
userOfficePlacesDoa.insertOffice(office1)
userOfficePlacesDoa.insertPlaces(places1)
var uopc: UserOfficePlacesCombined = userOfficePlacesDoa.getAllUserOfficePlacesCombined()
Log.d("UOPCINFO","User Name is " + uopc.user?.name + " Office Address is" + uopc.office?.address + " Places name is " + uopc.places?.name)
结果是:-
2019-10-16 22:35:16.442 D/UOPCINFO: User Name is USER1 Office Address isOffice1 Places name is Place1