春季数据重复键值

huangapple 未分类评论66阅读模式
标题翻译

Spring data duplicate key value

问题

我在PostgreSQL中有一张带有唯一约束的表,插入后我会收到错误信息duplicate key value violates unique constraint。在使用Spring Data时,跳过这个错误的最佳方法是什么(例如,使用ON CONFLICT DO NOTHING)?

英文翻译

I have a table in postgresql with unique constraint and after insert i can get the error duplicate key value violates unique constraint. How best way to skip this error (for example, ON CONFLICT DO NOTHING) using spring data?

答案1

得分: 1

如果您想在冲突的情况下忽略该行,只需使用 INSERT ... ON CONFLICT (field) DO NOTHING

英文翻译

If you want to forget the row in case of conflict, just use INSERT ... ON CONFLICT (field) DO NOTHING.

答案2

得分: 1

你可以捕获 DataIntegrityViolationException 异常,并按照您的需求进行处理,例如:

try {
    repository.save(myEntity);
} catch(DataIntegrityViolationException e) {
    System.out.println("Entity already exists. Skipping ...");
}
英文翻译

You can catch the DataIntegrityViolationException exception and handle it the way you want e.g.

try {
    repository.save(myEntity);
} catch(DataIntegrityViolationException e) {
    System.out.println("Entity already exists. Skipping ...");
}

huangapple
  • 本文由 发表于 2020年3月4日 02:53:00
  • 转载请务必保留本文链接:https://java.coder-hub.com/60513810.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定