gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-29 13:11:24 32 4
gpt4 key购买 nike

我使用以下代码将实体持久化到 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>{

}

它为大约 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

看起来 Postgres 从一开始就开始生成 ID,并忽略了已经存在的记录。重新启动没有帮助,也没有使用 EntityManager。应用程序适用于新的干净数据库。关于如何修复数据库以便生成的任何想法正确的 ID?

已解决:

创建表 tw_event2 作为表 tw_event;

然后我删除了原始表并将副本重命名为 tw_event。之后,下一个 ID 如预期的那样是 last+1。无需更改代码。虽然不知道是什么导致了这个错误

最佳答案

如果您当然不使用序列,最好指定像 @GeneratedValue(strategy = GenerationType.IDENTITY) 这样的策略,否则您将使用 @GeneratedValue(strategy = GenerationType.SEQUENCE) ,以确保用于生成 id 的策略始终相同。

关于java - 带有 Postgres 的 Spring JPA - 从一开始就重置 ID 生成,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54172183/

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