Hi I'm new to JPA and I want to validate a unique constraint, thought before making the insert to the persistence context, do a select to see if the data already exists, if not, return a boolean to proceed with the transaction .. is this a good alternative? Thank you very much.
Asked
Active
Viewed 536 times
0
-
Why not check to see if it exists? For example: [In JPA 2, using a CriteriaQuery, how to count results](http://stackoverflow.com/questions/2883887/in-jpa-2-using-a-criteriaquery-how-to-count-results). – K.Nicholas Oct 20 '14 at 16:50
-
yes already i think it, but it is the best and simple way? it´s a good practice? – Mariah Oct 20 '14 at 17:08
1 Answers
1
If you think you need to check first against the database then it'll work. Typically however, the reason you use a unique constraint is that you don't expect to have duplicates, so you wouldn't waste time checking, just be sure that you are aware when the error condition happens so you can figure out what went wrong. If you actually expect to have the same value many times but want singletons in the database, then you're asking a design question and perhaps should try programmers.stackoverflow.com.

Community
- 1
- 1

K.Nicholas
- 10,956
- 4
- 46
- 66
-
thanx Nicholas, duplication of data does not depend on me, but I think the user might enter a duplicate value, I'll check first if the value exists in the persistence context, if not, then it will insert. Thanks for the recommendation. – Mariah Oct 20 '14 at 18:26