Существует несколько вопросов и ответов о взаимоотношениях «многие ко многим» с использованием объединения баз данных в android комнате, написанной Kotlin
Но, например, я хочу определить класс A, имеющий список класса B
Как сделать запрос в Dao и сопоставить класс данных соединения с StudentHasSubjectList.class
ниже приведен тестовый код
https://github.com/woosuk0410/android-kotlin-room-many-to-many.git
Спасибо
@Entity
data class Student(@PrimaryKey @NonNull @ColumnInfo val studjentId: Int = 0, @NonNull @ColumnInfo val studjentName: String = "noname")
@Entity
data class Subject(@PrimaryKey @NonNull @ColumnInfo val subjectId: Int = 0, @NonNull @ColumnInfo val subjectName: String = "nosubject")
@Entity(
primaryKeys = arrayOf("stuId", "subId"),
foreignKeys = arrayOf(
ForeignKey(
entity = Student::class,
parentColumns = arrayOf("studjentId"),
childColumns = arrayOf("stuId"),
onDelete = ForeignKey.NO_ACTION
),
ForeignKey(
entity = Subject::class,
parentColumns = arrayOf("subjectId"),
childColumns = arrayOf("subId"),
onDelete = ForeignKey.NO_ACTION
)
), indices = [Index(value = ["stuId"]), Index(value = ["subId"])]
)
data class SSJoin(stuId: Int = 0, val subId: Int = 0)
data class StudentHasSubjectList(
val stduentId: Int = 0,
val studentName: String = "noname",
val subjectList: List<Subject>
)
@Dao
interface MyDao {
@Query("SELECT * FROM SSJoin")
fun getSSJoinList(): LiveData<List<SSJoin>>
@Insert
fun insert(studentSubjectJoin: SSJoin)
@Insert
fun insert(student: Student)
@Insert
fun insert(subject: Subject)
// @Query("SELECT * ")
// fun getStudjentHasSubjectList(): LiveData<List<StudentHasSubjectList>>
}
class MyViewModel(application: Application) : AndroidViewModel(application) {
val ssJoinList: LiveData<List<SSJoin>> = MyRoomDatabase.getDatabase(application, viewModelScope).myDao().getSSJoinList()
//val studentHasSubjectList: LiveData<List<StudentHasSubjectList>> = MyRoomDatabase.getDatabase(application, viewModelScope).myDao().getStudjentHasSubjectList()
}
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
val myViewModel = ViewModelProvider(this).get(MyViewModel::class.java)
myViewModel.ssJoinList.observe(this, Observer {
it?.let {
for(ssjoin in it) {
Log.e("My Application", ssjoin.toString())
}
}
})
//myViewModel.studentHasSubjectList.observe(this, Observer{})
}
}