I'm hardly the local database pundit, but I've always adhered to the principal that a business field should never be used as a primary key. You'd think that something like an employee ID would be safe to use, but what if (just as with social security numbers) they decide to start re-using them?
For primary keys I always use a Long value that has no meaning other than to serve as a primary key.
Jane Dodo wrote:
Alternatively: given an object, how do I know whether another object with the same id exists in the database? (but without knowing which fields constitute the object's id?
The only solution I can think of is parsing annotations and using reflection - yikes! There has to be an easier way.
Not sure can answer your question.
can you merge it first, then use session.getIdentifier()?
I gotta keep learning...
Joined: Mar 28, 2009
OK, maybe I should make it clear what exactly I am trying to do.
I am writing a Swing framework that edits an entity object. It works in two modes: creating new object, and editing an existing one. If it's creating a new object, and user enters an id that already exists in the database, the framework is to fail gracefully (i.e. tell the user that an object with this id already exists, please choose another id).
Unfortunately, it fails with a ConstraintViolationException, and, short of parsing the exception, it's impossible (as far as I can tell) to know whether a primary key or somethiing else has been violated.
If I do a Session.merge(), it will save to the database. I can always rollback that save (although undesirable); however, once it saved, how do I know whether a record already existed before merge?