如果数据模型(对象)发生变化,更新数据库的最佳方法是什么?
假设有一个 Teacher 对象,并且 Teachers 拥有一个 Courses 对象列表。 教师的课程可能会发生变化。有些被添加,有些被删除。 更新数据库中的此更改的最佳方法是什么? 1. 每次更改后,立即更新数据库。例如:添加课程后,立即将其添加到数据库中。 2. 对实体/对象教师进行所有更改(添加课程、删除课程)后,才使用所有更改更新数据库。 3.其他??
我可以看到1和2的优点和缺点。 对于1:我不知道当数据模型可以直接访问数据库时有多好。 对于2:算法更复杂,因为您必须同时将数据模型中的信息与数据库中的信息进行比较。
谢谢
Let's say theres a Teacher object and that Teachers holds a list of Courses objects.
The courses for the Teacher can change. Some get added, some get deleted.
What's the best approach to update this changes in the database.
1. Right after every change, update the database. e.g.: A course get added, immediately add that into the database as well .
2. After all changes are made to the entity/object Teacher (courses are added, courses are deleted), only then update the database with all the changes.
3. Others ??
I can see for both 1 and 2 advantages and disadvantages.
For 1: I don't know how good it is when data models have direct access to the database.
For 2: The algorithm its more complex because you have to compare the information in the data models with information in the database all at once.
Thank you
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
查看一些适用于您的语言或平台的 ORM 工具。数据库中实体的对象表示总是可能不同步。例如,如果用户更改了某个属性,并尝试更新数据库,但由于某种原因更新失败。现在这两个项目不同步。
它还可能取决于数据库的更新频率。如果您不希望在写入数据库方面发生大量活动,则可以选择在任何属性更改时触发即时数据库更新。
否则,您可以在对象中包含一个
dirty
标志,以指示它何时与数据库不同步。对象更改可以在发生时更新,或者在触发事件时更新,例如当用户决定保存其进度时,或者定期更新,例如每 x 分钟更新。不同的语言和框架以不同的方式实现这些模型对象。在 Rails 中,模型对象是 ActiveRecord 的子类,并且知道如何持久化自身到数据库中。在 Java 中,您很少会将域对象与其持久化方式混合在一起。这通常由 ORM 框架或自定义 DAO 对象来处理。
Take a look at some of the ORM tools available for your language or platform. An object's representation of an entity in the database can always get out-of-sync. For example, if a user changed a certain property, and a database update was attempted but for whatever reasons that update failed. Now these two items are not synchronized.
It may also depend on the frequency of updates to your database. If you don't expect massive activity in terms of writes to the database, triggering instant database updates on any property change may be an option.
Otherwise, you may include a
dirty
flag in your object to indicate when it goes out of sync with the database. Object changes could be updated as they happen, or when a event is triggered such as when the user decides to save their progress, or periodically, say every x minutes.Different languages and frameworks implement these model objects differently. In Rails, a model object is subclasses from ActiveRecord and knows how to persist itself into a database. In Java, you would rarely mix domain objects with the way they're persisted. That's usually taken care of by an ORM framework or custom DAO objects.
我发现了 Hibernate。这正是我所需要的,而且很简单。
I found out about Hibernate. It's exactly what i need and it's simple.