在下面的函数中,我正在更新一个用户。但是用户有一个"createdDate"字段,该字段将位于数据库中,但不会在客户端传递的用户实体中:
def update(user: User): Future[Int] = {
db.run(
userTable
.filter(_.userId === user.userId)
// Can I set user.createdDate here to the existing value?
.update(user)
)
}
在调用 update(user( 之前,是否可以使用 db 中现有用户行的值来设置 user.createdDate?
作为参考,以下是我在创建用户时如何设置 createdDate 字段(用户是一个不可变的案例类,所以我做了一个副本来设置 createdDate(:
def create(user: User): Future[Int] = {
db.run(userTable += user.copy(
createdDate = Option(Timestamp.valueOf(LocalDateTime.now()))))
}
您可以像这样解构用户对象并跳过createdDate
。
userTable
.filter(_.id === id)
.map(t => (t.firstName,..., t.modifiedDate))
.update(("John",..., Some(Timestamp.valueOf(LocalDateTime.now))))
我最终只是在更新前进行了阅读,如下所示:
this.read(user.userId).flatMap {
case Some(existingUser) =>
db.run(
userTable.
filter(_.userId === user.userId).
update(user.copy(createdDate = existingUser.createdDate)))
case None => throw new NotFoundException(...)
}