英文:
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 ...");
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论