Reputation: 23587
I need to create gift card entity in DB where gift card codes are being generated by an algorithm and chances of their collision are quite low.
Still before inserting gift card entities in DB , we need to check the possibilities of duplicate gift card entities.
Also need to take care following points
I am using Hibernate for DB operations and I have following options.
I am a little confused about which approach should be preferable ?
Upvotes: 1
Views: 2652
Reputation: 693
To make sure that duplicates are not allowed, you must have a unique index and/or a unique constraint on the column used to store your gift card codes.
That said, I would recommend the first option because it is more efficient if there is low chances of gift card code duplicates. Also in the second option, even if you check for duplicates before inserting new codes, you have no guarantee that a code with the same value has not been inserted in the DB between your check and insertion, so you would also have to handle the case when insertion throws a constraint exception.
Upvotes: 1
Reputation: 1912
I would create all and then would check for duplicated values with a JPQL lilke:
select p from Ticket p where p.id in (:idList)
With this kind of "batch" operation you would not need to make a trip to the database at each iteration. That is the problem of your first option.
If you use somekind of database rule, e.g.: constraint or trigger, you could receive a exception that could cause your transaction to rollback.
Upvotes: 0