Meaningless Drivel is fun!*
The moose likes Object Relational Mapping and the fly likes JPA optional uniqueness check possible? Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


JavaRanch » Java Forums » Databases » Object Relational Mapping
Bookmark "JPA optional uniqueness check possible?" Watch "JPA optional uniqueness check possible?" New topic
Author

JPA optional uniqueness check possible?

R van Vliet
Ranch Hand

Joined: Nov 10, 2007
Posts: 144
Hey guys,

We have the following problem that I'm hoping you guys have a solution for :

We have a table "Item" with a column "name". We want to be able to determine in a consistent, concurrency safe way that we can add a new record of type "Item" with a value for "name" that is unique. As most readers will know JPA only supports optimistic locking but we have no issues with using vendor specific pessimistic locking. That said I still cannot figure out a good way to do something like this without using database level uniqueness constraints which is something we really want to avoid (we do not always have access to client databases and whether or not this field has to be unique is an application setting that varies across different deploys for us, so doing it on an app level is a lot easier for us). Is there a way to do this without table locks?

I hope someone has a good suggestions for us, thanks!
Ralph Jaus
Ranch Hand

Joined: Apr 27, 2008
Posts: 342
Appropriate data access layer design depends on characteristics of the application like data volume, performance requirements (do you need fast inserts, selects, both ?), average number of concurrent requests, etc. Therefore, based on your information, it will be difficult to give proper suggestions.

However, the following came into my mind:
1. insert the item record
2. commit the transaction
3. count the number of records having the same name like the record that has just been inserted
4 if the number is greater than one, remove the record again

Remarks:
- It's possible that both records of two concurrent requests will be refused.
- Concerning uniquness of names, the database may be in inconsistent state during steps 3 and 4. However, if a timestamp is available and there is a request, that selects a record for the name in question, you know by timestamp that the older record is the correct one and the other only exists temporarily.
- If data volume is large it surely needs an index or some other database facility to make the select count work with good performance.

Anyway, it's an interesting problem. Please, let us know about your solution.


SCJP 5 (98%) - SCBCD 5 (98%)
 
GeeCON Prague 2014
 
subject: JPA optional uniqueness check possible?