简体   繁体   English

带有 Postgres 的 Spring JPA - 从一开始就重置 ID 生成

[英]Spring JPA with Postgres - ID generation reset from start

I was using following code to persist an entity to Postgres:我使用以下代码将实体持久化到 Postgres:

@Entity
public class TwEvent {

    @Id
    @GeneratedValue
    private Long id;

    private String type;
}



@Repository
public class TwEventDAO {

   @Autowired
   private TwEventRepo repo;

   public void save(TwEvent twEvent) {
     repo.save(twEvent);
   }
}


public interface TwEventRepo extends JpaRepository<TwEvent,Long>{

}

It was working for ~30.000 records, but when I launched my app today, I get SQL error:它适用于大约 30.000 条记录,但是当我今天启动我的应用程序时,出现 SQL 错误:

2019-01-13 19:57:48:432 WARN  http-nio-8081-exec-4 o.h.e.j.s.SqlExceptionHelper:127 - SQL Error: 0, SQLState: 23505
2019-01-13 19:57:48:432 ERROR http-nio-8081-exec-4 o.h.e.j.s.SqlExceptionHelper:129 - ERROR: duplicate key value violates unique constraint "tw_event_pkey"
  Detail: Key (id)=(34) already exists.
2019-01-13 19:57:48:434 INFO  http-nio-8081-exec-4 o.h.e.j.b.i.AbstractBatchImpl:193 - HHH000010: On release of batch it still contained JDBC statements

Looks like Postgres started generating Ids from start and ignores already existing records.看起来 Postgres 从一开始就开始生成 Id 并忽略已经存在的记录。 Restarting didn't help, neither using EntityManager.重新启动没有帮助,也没有使用 EntityManager。 App works fine with new clean DB.应用程序与新的干净数据库一起正常工作。 Any ideas how to fix a DB so it would generate right id?任何想法如何修复数据库,以便它会生成正确的 id?

SOLVED:解决了:

CREATE TABLE tw_event2 AS TABLE tw_event;创建表 tw_event2 作为表 tw_event;

then I removed the original table and renamed a copy to tw_event.然后我删除了原始表并将副本重命名为 tw_event。 After that next ID was last+1 as expected.之后,下一个 ID 是 last+1,正如预期的那样。 There was no need to change the code.无需更改代码。 No idea what caused this error though不知道是什么导致了这个错误

如果您当然不使用序列,则最好指定类似@GeneratedValue(strategy = GenerationType.IDENTITY)否则您将放置@GeneratedValue(strategy = GenerationType.SEQUENCE) ,以确保用于生成 id 的策略是总是一样。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM