gpt4 book ai didi

java - 在NoSQL系统中,例如每个Lesson有很多Exercise,在插入Exercise之前我们需要检查Lesson是否存在两次吗?

转载 作者:行者123 更新时间:2023-11-30 07:41:50 24 4
gpt4 key购买 nike

好的,LessonNo 是类(class)表的 ID,LessonNo 是练习的外键。每课有很多练习,但每个练习只属于 1 课。

这是图形用户界面

Text Box "Lesson No":....Text Area "Exercise":......Button "Insert Exercise": 

When user click "Insert Exercise", the system will check if Lesson exists. If it does then they will call insertExercise (String exercise) method

public boolean checkIfThisLessonNoExists(int lessonNo){
//query from datastore
return true or false;
}
if(checkIfThisLessonNoExists(lessonNo)){
insertExercise (exercise);
}
public boolean insertExercise (String exercise){
Transaction tx=datastore.beginTransaction();
try{
Entity e=new Entity("Exercise");
e.setProperty("exercise",exercise);
datastore.put(e);
tx.commit();
}
catch{
}
}

如果我们确实像上面那样,那么会有什么问题吗?

在 Google App Engine 或任何 NoSQL 系统中,不存在外部约束。那么,如果我们在插入时类(class)被删除了怎么办???

解决这个问题。我们需要在 Transaction 中再次检查 lesson 吗?

那么,我们应该这样做吗?:

  public boolean insertExercise (int lessonNo, String exercise){
Transaction tx=datastore.beginTransaction();
try{
if(checkIfThisLessonNoExists(lessonNo)){
Entity e=new Entity("Exercise");
e.setProperty("exercise",exercise);
datastore.put(e);
tx.commit();
}
else{
tx.rollback();
}
}
catch{
}
}

最佳答案

您所描述的系统无法阻止插入无效的 Exercise - Lesson可以随时删除或以其他方式失效,因此即使您添加 checkIfThisLessonNoExists(lessonNo)检查insertExercise的内部所有这一切都会减少插入无效 Exercise 的可能性。而不消除这种可能性。

最简单的解决方案是接受您的数据存储不会 100% 一致的事实,并在查询时(即查询 Exercises 组时)采取纠正措施。你应该过滤掉任何 Exercise与不存在的 Lesson 相关联并让用户知道 Exercises 的列表您返回的仅对该时间戳有效,不能反射(reflect) Lessons 的任何更改或Exercises在稍后的时间戳生效。 (我不建议您在执行此查询时删除无效的 Exercises,因为这可能会将只读查询转换为读写查询 - 相反,安排清理过程以定期从存储中删除无效数据。)

关于java - 在NoSQL系统中,例如每个Lesson有很多Exercise,在插入Exercise之前我们需要检查Lesson是否存在两次吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34562763/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com