DAO设计用于更新数据库中的实体。

huangapple go评论85阅读模式
英文:

DAO design to update an entity in DB

问题

客户端更新实体(例如:学生实体)的情况下,我们会获取学生的ID以及客户端修改过的其他字段(不是所有字段)。

我了解到我们应该将特定的实体对象传递给DAO以进行更新。
但是,我将如何获取该实体对象呢?因为我没有所有字段的数据来创建正确的实体对象。

我应该进行两次数据库调用吗?

第一次调用是为了构建正确的实体对象,然后通过将此更新后的实体对象传递给DAO来进行更新。

英文:

Lets say a client updates an entity ( Ex: student entity ).
So we get the student Id and other modified fields (not all fields) from the client.

I read that we should pass the particular entity object to DAO in order to update.
But then , how will I get to form that entity object.Because I don't have all fields data to create a proper entity object.

Should I make two DB calls ?

The first call is to construct a proper entity object and then make the update by passing this updated entity object to the DAO.

答案1

得分: 2

唯一避免进行两次数据库调用的方法是使用更新语句仅更新您拥有的字段。例如:

UPDATE Student SET someField1 = :field1, someField2 = :field2 WHERE ID = :id

请记住,更新查询会绕过乐观锁定检查。如果您使用乐观锁定,应将版本附加到where子句,并递增它。

UPDATE Student SET someField1 = :field1, version = version + 1 WHERE id = :id AND version = :version

在执行executeUpdate之后,您应该检查受影响的行数:

  • 1:一切正常
  • 0:实体可能无法通过其id找到。也许它在此期间被删除,或者版本不匹配。在这两种情况下,您应该引发OptimisticLockException。
  • 1:您应该引发异常以回滚事务。

英文:

The only way to avoid two DB calls is to use an update statement to update only th fields you have. E.g.

UPDATE Student SET someField1 = :field1, someField2 = :field2 WHERE ID = :id

Remember that update queries bypass optimistic locking checks.
If you use optimistic locking you should append the version to the where clause and also increment it.

UPDATE Student SET someField1 = :field1, version = version + 1 WHERE id = :id AND version = :version

After an executeUpdate you should check the affected rows:

  • 1 : everything is ok
  • 0 : the entity could either not be found by it's id. Maybe it was deleted in the meanwhile or the version did not match. In both cases you should raise an OptimisticLockException.
  • >1 : you should raise an exception to rollback the transaction.

huangapple
  • 本文由 发表于 2020年8月4日 23:48:41
  • 转载请务必保留本文链接:https://go.coder-hub.com/63250497.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定