Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.2k views
in Technique[技术] by (71.8m points)

java - Best way to detect duplicates when using Spring Hibernate Template

We have an application which needs to detect duplicates in certain fields on create. We are using Hibernate as our persistence layer and using Spring's HibernateTemplate. My question is whether it is better to do so an upfront lookup for the item before creating, or to attempt to catch the DataIntegrityViolation exception and then check if this is caused by a duplicate entry.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

It depends on whether having a duplicate is an exceptional scenario, or a business-logic case.
For example, checking for unique email/username during registration is a business-logic case and the check should be done before trying to insert

If you are required to indicate which field exactly has failed with the unique constraint, you'd better check it beforehand, rather than catching the exception. Catching the exception doesn't give you the important detail - which field has failed.

There are ways to obtain this information, based on the exception, but it is very tedious and is database-specific (lookup the constraint name in the DB (db-specific), get the field it is applied on, match the field with the entity property)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

57.0k users

...