要在Android Room中编写自定义嵌套对象,你可以按照以下步骤进行操作:
@Entity(tableName = "users")
data class User(
@PrimaryKey
val id: Int,
val name: String,
val address: Address
)
data class Address(
val street: String,
val city: String,
val state: String,
val country: String
)
@Dao
interface UserDao {
@Query("SELECT * FROM users")
fun getAllUsers(): List
@Insert
fun insertUser(user: User)
}
@Dao
interface AddressDao {
@Insert
fun insertAddress(address: Address)
}
@Database(entities = [User::class, Address::class], version = 1)
abstract class AppDatabase : RoomDatabase() {
abstract fun userDao(): UserDao
abstract fun addressDao(): AddressDao
}
class MyApp : Application() {
companion object {
lateinit var database: AppDatabase
}
override fun onCreate() {
super.onCreate()
database = Room.databaseBuilder(this, AppDatabase::class.java, "my-database")
.build()
}
}
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
val userDao = MyApp.database.userDao()
val addressDao = MyApp.database.addressDao()
val address = Address("123 Street", "City", "State", "Country")
val user = User(1, "John", address)
addressDao.insertAddress(address)
userDao.insertUser(user)
val users = userDao.getAllUsers()
// 处理users数据
}
}
这样,你就可以使用Android Room编写自定义嵌套对象了。当你查询数据库时,Room会自动处理嵌套对象的关联关系。