标题翻译
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 ...");
}
专注分享java语言的经验与见解,让所有开发者获益!

评论