【问题标题】:Restart Id=1 when deleting every record in a table? (Angular + Spring Boot + MySQL)删除表中的每条记录时重新启动Id = 1? (角度 + Spring Boot + MySQL)
【发布时间】:2021-09-14 12:01:44
【问题描述】:

我正在开发一个简单的 CRUD 应用程序,前端使用 Angular,后端使用 Spring Boot,数据库使用 MySQL。

我已经设法插入、检索和更新/删除表中的值,但是当我从 CRUD 中删除所有记录时,我正在努力重新启动 Id 的值(我设置为主键)桌子。我的意思是,如果我有 10 条记录(Id = 1,...,10)并且我删除了所有记录,那么下一次插入的 Id=1 并且我希望它等于 1。我正在使用InnoDB 作为引擎。

前端部分-

.html 文件

  <button class="m-3 btn btn-sm btn-danger" (click)="removeAllRecords()">
    Remove All
  </button>

.ts 文件

  removeAllRecords(): void {
if(confirm("Are you sure you want to delete ALL your records?")){
this.recordService.deleteAll()
  .subscribe(
    response => {
      console.log(response);
      this.refreshList();
    },
    error => {
      console.log(error);
    });
  }
}

service.ts 文件

const baseUrl = 'http://localhost:8080/api/records';

deleteAll(): Observable<any> {
return this.http.delete(baseUrl);
}

后端部分 - 我在 Spring Boot 上使用 Datajpa 存储库:

模型文件

@Entity
@Table(name = "crud")
public class Record{
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private long id;
....
}

控制器文件

@DeleteMapping("/records")
public ResponseEntity<HttpStatus> deleteAllRecords() {
    try {
        contactRepository.deleteAll();
        return new ResponseEntity<>(HttpStatus.NO_CONTENT);
    } catch (Exception e) {
        return new ResponseEntity<>(HttpStatus.INTERNAL_SERVER_ERROR);
    }

}

现在,我认为必须在上面的函数中或在表的定义上做一些事情,但我不明白是什么以及如何......请你帮帮我吗?

附:我在 application.properties 文件中使用这些设置:

spring.datasource.url= jdbc:mysql://localhost:3306/codejavadb?useSSL=false
spring.datasource.username= root
spring.datasource.password= *pwd*
spring.jpa.show-sql=true
spring.jpa.properties.hibernate.dialect= org.hibernate.dialect.MySQL5InnoDBDialect
spring.jpa.hibernate.ddl-auto= update

希望我说清楚了,我对所有这些工具和语法都很陌生,任何帮助将不胜感激,谢谢! :)

【问题讨论】:

    标签: javascript mysql angular spring spring-boot


    【解决方案1】:

    您可以直接添加一个逻辑来设置主键。在进行任何插入之前,请检查记录数。如果有记录,则下一个主键为+1。如果没有记录,它将返回 0,因此 +1 会将主键作为 1 分配给该插入。

    【讨论】:

    • 我会在哪一部分添加这个逻辑?在我在 Spring Boot 中定义的函数中?无论如何,“@GeneratedValue(strategy = GenerationType.IDENTITY)”中的逻辑不是已经存在了吗?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-07-02
    • 1970-01-01
    • 2018-05-18
    • 2023-01-15
    • 2013-02-26
    • 2021-03-17
    • 1970-01-01
    相关资源
    最近更新 更多