如何在Kotlin中向房间数据库添加模型类

zbdgwd5y  于 2022-11-16  发布在  Kotlin
关注(0)|答案(1)|浏览(171)

我有一个保存的模型,我需要添加到我的数据库。我怎样才能把它们导入到我的数据库。下面是模型类。

{
"AccountNumber": "S234567",
"ActionRequiredID": "6,7",
"AdditionalRemarks": "",
"AndroidVersion": "31",
"AntennaTypeID": 6,
"AppVersion": "2.1.3",
"CTRatio": "",
"CategoryID": 1,
"CurrentMeterSealNumber": "thhjj",
"CycleName": "Nov-2022",
"EndTime": "2022-11-07 12:05:51",
"ICCIDNumber": "thb",
"Images": [
    {
        "ID": 0,
        "PicFormat": "jpg",
        "PicName": "S23456-TRS_6-TI1-team1_2022-11-07_17-35-05.jpg",
        "PicPath": "/storage/emulated/0/Download/team1/MReader/troubleshoot/Troubleshooting-Nov-2022/Photos/",
        "PicSize": "36 KB",
        "PictureTypeID": 18,
        "ServiceID": 5,
        "SurveyID": 6
    }
],
"IsGPSEnabled": true,
"IsLiveGPS": true,
"IsOnline": true,
"Latitude": 11.0501224,
"LocationAccuracy": 9.133,
"LocationProvider": "fused",
"Longitude": 76.9678775,
"MeterLocationID": 1,
"MeterModelID": 5,
"MeterSerialNumber": "61604448",
"NewMeterSealNumber": "",
"PingTestID": 1,
"ReasonForFailureID": "5",
"ReasonID": 39,
"Remarks": "",
"Seal1": "",
"Seal2": "",
"Seal3": "",
"Seal4": "",
"ServiceID": 5,
"SignalLevelID": 2,
"SimInField": "cghb",
"StartTime": "2022-11-07 12:05:05",
"StatusID": 12,
"StatusTroubleshootID": 4,
"UserID": 161,
"WorkOrderID": 6,
"WorkOrderNumber": "TRS_6",
"reason": "Completed",
"status": "Completed"

}
List以外的信息需要添加到名为“ReplacedData”的单独表中,图像则添加到“Images”中。
我应该怎么做,对此有什么疑问?

vsdwdz23

vsdwdz231#

第1步基于模型创建一个@Entity(也称为表)注解类,表名为ReplacedData(根据 * List以外的信息需要添加到一个名为“ReplacedData”的单独表中 *)类,List字段具有@Ignore注解。
第2步基于Image类创建一个@Entity(第2个表)注解类,其中包含一个附加字段,用于存储所属ReplacedData行的主键(假设存在一对多关系,即图像可以有一个父代ReplacedData)

  • 可以选择包含ForeignKey定义以强制引用完整性
  • 可以选择对CASCACDE执行onDelete和onUpdate操作,从而帮助维护参照完整性

步骤3创建一个POJO,用于提取ReplacedData行沿着图像(子级),其中步骤1中的类是@Embedded,步骤2中的类是@Relation
例如,考虑以下工作示例(具有缩减的类):

步骤1

@Entity
data class ReplacedData(
    @PrimaryKey
    val replacedDataId: Long?=null,
    val AccountNumber: String,
    val ActionRequired: String,
    val AdditionalRemarks: String,
    val AndroidVersion: Int,
    val AppVersion: String,
    /* etc */
)
  • 请注意,不确定AccountNumber是否是唯一的,是否适合主键,因此添加了replacedDataId。
    步骤2
@Entity(
    /* Optional but suggested to enforce referential integrity */
    foreignKeys = [
        ForeignKey(
            entity =  ReplacedData::class,
            parentColumns = ["replacedDataId"],
            childColumns = ["parentReplacedData"],
            onDelete = ForeignKey.CASCADE,
            onUpdate = ForeignKey.CASCADE
        )
    ]
)
data class Images(
    @PrimaryKey
    val imageId: Long?=null,
    @ColumnInfo(index = true)
    val parentReplacedData: Long,
    val ID: Long,
    val PicFormat: String,
    /* etc */
)
  • 再次添加特定主键
  • 具有CASCADE的外键,以便实施和维护参照完整性
    步骤3
data class ReplacedDataWithImages(
    @Embedded
    val replacedData: ReplacedData,
    @Relation(
        entity = Images::class,
        parentColumn = "replacedDataId",
        entityColumn = "parentReplacedData"
    )
    val imagesList: List<Images>
)

演示的附加内容

data class TheModel(
    val replacedData: ReplacedData,
    val ImageList: List<Images>
)
  • 类似于Model类(但通过基于@Entity注解类对其进行简化而作弊)

:-

@Dao
interface AllDao {
    @Insert(onConflict = OnConflictStrategy.IGNORE)
    fun insert(replacedData: ReplacedData): Long
    @Insert(onConflict = OnConflictStrategy.IGNORE)
    fun insert(images: Images): Long

    @Transaction
    @Query("")
    fun insert(theModel: TheModel) {
        val replacedDataId = insert(theModel.replacedData)
        var imagesInserted=0
        if (replacedDataId > 0) {
            for(i: Images in theModel.ImageList) {
                if (insert(Images(parentReplacedData = replacedDataId, ID = i.ID, PicFormat = i.PicFormat)) > 0) {
                    imagesInserted +=1
                }
            }
        }
    }

    @Transaction
    @Query("SELECT * FROM replaceddata")
    fun  getAllFromReplacedDataWithImages(): List<ReplacedDataWithImages>
}
  • 3个用于插入的函数,请注意,第3个函数采用**TheModel**,并插入ReplacedData和具有对父级的正确引用的相关图像(子级)。

:-

@Database(entities = [ReplacedData::class,Images::class], exportSchema = false, version = 1)
abstract class TheDatabase: RoomDatabase() {
    abstract fun getAllDao(): AllDao

    companion object {
        private var instance: TheDatabase? = null
        fun getInstance(context: Context): TheDatabase {
            if (instance==null) {
                instance = Room.databaseBuilder(context,TheDatabase::class.java,"thedatabase.db")
                    .allowMainThreadQueries() /* to allow demo to use the main thread for brevity */
                    .build()
            }
            return instance as TheDatabase
        }
    }
}
  • 一个带有@Database注解的基本类沿着一个单例方法
  • 注意,为了简洁起见,它允许使用主线程,
    最后一句
class MainActivity : AppCompatActivity() {

    lateinit var db: TheDatabase
    lateinit var dao: AllDao
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        db = TheDatabase.getInstance(this)
        dao = db.getAllDao()

        val listOfImages = listOf<Images>(
            Images(parentReplacedData = 0, ID = 0, PicFormat = "JPG"),
            Images(parentReplacedData = -1, ID = 10, PicFormat = "GIF"),
            Images(parentReplacedData = 0, ID = 100, PicFormat = "GIF")
        )

        dao.insert(
                TheModel(
                    ReplacedData(
                        AccountNumber = "S1234567",
                        ActionRequired = "doit",
                        AdditionalRemarks = "quickly",
                        AndroidVersion = 31,
                        AppVersion = "2.3.1"
                    ),
                    listOfImages
                )
        )

        val sb = StringBuilder()
        for (rdwi in dao.getAllFromReplacedDataWithImages()) {
            sb.clear()
            for (i in rdwi.imagesList) {
                sb.append("\n\t ID=${i.ID}  Parent=${i.parentReplacedData} ImageId=${i.imageId} PivFormat=${i.PicFormat}")
            }
            Log.d("DBINFO"," Account Number=${rdwi.replacedData.AccountNumber} Image Count = ${rdwi.imagesList.size}. They are:-${sb}")
        }
    }
}
  • 一些活动代码插入一些数据,然后提取它,将相关数据写入日志。

运行时(仅设计为运行一次),日志包含:-

D/DBINFO:  Account Number=S1234567 Image Count = 3. They are:-
         ID=0  Parent=1 ImageId=1 PivFormat=JPG
         ID=10  Parent=1 ImageId=2 PivFormat=GIF
         ID=100  Parent=1 ImageId=3 PivFormat=GIF

使用应用程序检查,然后:-

相关问题