如果 2 个组合列不存在,则初始化房间数据库

问题描述 投票:0回答:2

我有一张带有一些柱子的房间表。 enter image description here

现在我想添加另一列。但仅当“年”和“周”的组合不存在时才应添加。否则应该忽略。

@Insert(onConflict = OnConflictStrategy.IGNORE)
suspend fun initInsertWeek(week: Week)

如何通过查询存档?

这是“一周”

@Entity(tableName = "Weeks")

数据类周(

@PrimaryKey(autoGenerate = true)
val id: Long? = null,

val year: Int,
val week: Int,
val workingTime: Int,

@ColumnInfo(name = "timeStamp", defaultValue = "0")
val timeStamp: Long = 0,

@ColumnInfo(name = "weeklyWorkingDayCount", defaultValue = "5")
val weeklyWorkingDayCount: Int = 5,

@ColumnInfo(name = "weekDailyDurations", defaultValue = "462:462:462:462:462:0:0")
val weekDailyDurations: String = "462:462:462:462:462:0:0"

希望你能帮助我。

android sql kotlin android-room
2个回答
0
投票

您应该对实体使用独特的约束,如下所示,

import androidx.room.ColumnInfo
import androidx.room.Entity
import androidx.room.Index
import androidx.room.PrimaryKey

@Entity(
    tableName = "weeks",
    indices = [Index(value = ["year", "week"], unique = true)]
)
data class Week(
    @PrimaryKey(autoGenerate = true)
    val id: Long? = null,

    val year: Int,
    val week: Int,
    val workingTime: Int,

    @ColumnInfo(name = "timeStamp", defaultValue = "0")
    val timeStamp: Long = 0,

    @ColumnInfo(name = "weeklyWorkingDayCount", defaultValue = "5")
    val weeklyWorkingDayCount: Int = 5,

    @ColumnInfo(name = "weekDailyDurations", defaultValue = "462:462:462:462:462:0:0")
    val weekDailyDurations: String = "462:462:462:462:462:0:0"
)

实现 initInsertWeek 方法,在插入之前检查现有条目:

@Dao
interface WeekDao {
    @Insert(onConflict = OnConflictStrategy.IGNORE) // Ignore if the entry exists
    suspend fun insert(week: Week)

    @Query("SELECT * FROM weeks WHERE year = :year AND week = :week")
    suspend fun getWeek(year: Int, week: Int): Week?

    @Transaction
    suspend fun initInsertWeek(week: Week) {
        // Check if the week already exists
        val existingWeek = getWeek(week.year, week.week)
        if (existingWeek == null) {
            // If it doesn't exist, insert it
            insert(week)
        }
    }
}

现在就打电话吧

 weekDao.initInsertWeek(week)
 weekDao.initInsert(week) //Try this also

0
投票

您可以定义一个

  1. UNIQUE 两列上的索引,以及
  2. 使用
    INSERT OR IGNORE
    (无论如何你都可以使用
    @Insert(onConflict = OnConflictStrategy.IGNORE)

由于索引需要由多列组成(即它是复合索引),因此您需要使用

indicies
注释的
@Entity
参数。

对于年和周列的复合索引,您可以使用:-

@Entity(tableName = "Weeks",
    indices = [Index("year","week", unique = true)]
)
© www.soinside.com 2019 - 2024. All rights reserved.