【问题标题】:Two rows are inserted into DB table instead of one将两行插入数据库表而不是一行
【发布时间】:2021-01-23 04:52:15
【问题描述】:

我正在使用 Angular 作为前端、spring boot 作为 REST API 和 MySQL 作为数据库来构建一个完整的堆栈 Java 应用程序。我正在对学生对象进行 CRUD 操作。读取、更新和删除操作运行良好,但是当我尝试创建一个新学生时,两条记录被插入到数据库中,并且具有相同的详细信息(除了唯一的 student_id)而不是一个。我创建了一个新学生表单来创建一个新学生,并且同样的表单也用于更新现有学生。

单击表单中的“保存”按钮后,将转到以下方法:

save(){
    if(this.id == -1) { 
      this.studentService.createStudent(this.student)
          .subscribe (
            data => {
              console.log(data)
              this.router.navigate(['students'])
            }
          )
    } else {
      this.studentService.updateStudent(this.id, this.student)
          .subscribe (
            data => {
              console.log(data)
              this.router.navigate(['students'])
            }
          )
    }
  }

我调试过,发现这个方法被调用了两次,studentService.createStudent被调用了两次。我不知道为什么会这样。更新操作也使用相同的方法,但当时只调用一次。

【问题讨论】:

  • 您需要显示表单代码。 save() 函数是如何调用的?
  • 也添加html代码

标签: mysql angular spring spring-boot


【解决方案1】:

添加休息;或返回;数据插入数据库后,该方法不可能被调用两次。

【讨论】:

  • 在您的代码中放置断点,执行某些操作并检查值以及您的代码将如何运行。
【解决方案2】:

我已经找到了解决这个问题的方法。如果学生已经插入数据库表,则在组件文件中创建标志 studentUpdated 以存储状态:

studentUpdated: Boolean

然后仅当标志为 false 时才创建新学生,否则只会更新学生的现有详细信息。更新保存方法如下:

save(){
    if(this.studentUpdated===false){
    if(this.id == -1) { 
      this.studentService.createStudent(this.student)
          .subscribe (
            data => {
              console.log(data)
              this.router.navigate(['students'])
            }
          )
          this.studentUpdated=true;          
    } else {
      this.studentService.updateStudent(this.id, this.student)
          .subscribe (
            data => {
              console.log(data)
              this.router.navigate(['students'])
            }
          )
    }
    this.studentUpdated=true;    
  }
  }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-05-11
    • 1970-01-01
    • 1970-01-01
    • 2020-07-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-01-26
    相关资源
    最近更新 更多