I agree with the direction of Hibernate and the manuals that stress the use of surrogate keys for tables. This simplifies RI and makes more sense than relying on the "unchangeable" business attributes. I am looking for ideas on how others handle the requirements for uniqueness of business attributes.
Example:
A course at a college has a number that is unique within a department and a description
Math 101 Introduction to Calculas
English 101 The Plays of Shakespeare
A typical schema for this would be
id long
dept char(25)
coursenum char(3)
description char(50)
primarykey (id)
unique index (dept, coursenum)
The four approaches I see are:
1) Handle Hibernate Exceptions when the Course object is saved and the unique index constraint is violated.
2) Intercept the save, check for duplicate values and throw an application specific exception.
3) Implement business logic in the Course setters to check for duplicates and throw an application specific exception
4) #3 with either 1 or 2
Pros (+) /cons (-)
#1
+ Minimizes additional code
+ Smallest performance impact on majority of updates (no constraint violation)
- Late notification to end users
- If saved with dependent objects (Teachers, Students, Sections), will cause all work to be unsaved.
? will Hibernate identify the reason for the failure in an consistent / easy manner
#2
+ Flexiblility of coded solution, i.e. can be as complex as needed
- Some code but essentially boilerplate (might be able to implement pattern to refactor)
- would probably require a query to the table in the middle of an update
#3
+ Flexiblility of coded solution, i.e. can be as complex as needed
+ Quicker notification to user
+ Makes domain object more responsible for correct behavior
- Additional code
- Does not guarantee data integrity will not be violated outside the app
- May require more queries against the db to get list of current courses
- May still be possible to have constraint violation if 2 users insert the same record at the same time (dirty read vs committed read)
#4
+ quick notification
+ ensures data integrity will not be violated outside the app
- most code
Anyone have additional solutions, pros/cons or see something that I missed? How do you handle similar requirements in your applications? If you use multiple approaches, what criteria do you use to determine the best approach?
Thanks for taking the time to read my post!
Timothy Vogel