I have an entity representing Documents that looks like this:
Document
date_creation
doc_number
doc_origin
Documents are usually referred to as ‘2012/XY/005’, that would be the fifth document in 2012 originated by XY.
So number has to be unique in the year it was created and for the same Origin, and I need to put a constraint for it.
What would be the best way to model and map this using JPA?
I think my options are:
Option 1: put another field the Document entity for the year in date creation, and make it unique(year,doc_number,doc_origin)
Option 2: create a field doc_ref and put a string like ‘YEAR/ORIG/NUMBER’ and make it unique(doc_ref)
Both options add another field duplicating the year, but Option 1 requires me to update field year consistently with date_creation and Option 2 requires me to update field doc_ref consistently with the rest, so I tend to think that Option 1 is best.
Is there another option that I am not seeing?
Thanks!
You could use a function-based unique index, if your database allows them. Example in Oracle: