这个问题与上一个问题有关。但由于这个问题已经结束,我必须创建一个单独的问题。用例是这样的:我有一个有 5 列的表。创建记录时,只需要 2 列。稍后用户将向同一记录添加更多信息。例如,具有以下结构的用户表:id | 电话 | 电子邮件 | 信用 | 等级。当用户注册时,我只需要他们的电子邮件地址。将使用 ID 和电子邮件创建用户。稍后,用户想要添加电话号码,积分,当该用户有足够的积分时,系统也会更新级别。我创建了一个
case class User(id:UUID, phone:Option[String], email:Option[String],
credit:Option[Double], level:Option[String]
我也有
sealed class Users extends CassandraTable[Users, User] {
object id extends UUIDColumn(this) with PartitionKey[UUID]
object phone extends OptionalStringColumn(this)
object email extends OptionalStringColumn(this)
object credit extends OptionalDoubleColumn(this)
object level extends OptionalStringColumn(this)
def fromRow(row: Row): User = {
User(id(row), phone(row), email(row), credit(row), level(row))
}
}
我在使用可选列吗?我应该如何处理用户更新一个或多个特定列的用例?我尝试了这样的更新方法
def updateUser(u: User): Future[ResultSet] = {
update.where(_.id eqs u.id).modify(_.phone setTo u.phone)
.and(_.email setTo u.email)
.and(_.credit setTo u.credit)
.and(_.level setTo u.level)
.consistencyLevel_=(ConsistencyLevel.QUORUM)
.future()
}
此方法效果不佳,因为您必须从 id 读取表并使用现有列值创建一个 User 对象并添加新值,然后更新记录。在更新方法中写很多条件也是不现实的。如果我有很多列并且每一列都可以单独更新,我将不得不编写一个巨大的可能值组合列表。以下方法可能有效:
if(u.phone != None) update.where(_.id eqs u.id).modify(_.phone setTo u.phone).future
if(u.email != None) update.where(_.id eqs u.id).modify(_.email setTo u.email).future
if(u.credit != None) update.where(_.id eqs u.id).modify(_.credit setTo u.credit).future
......
但我不确定这是一个好习惯,因为如果您想在每次更新时处理更新失败,这将是一场噩梦。我应该如何使用可选列来实现我所需要的?