Unique Constraints allow a user to define a field to be unique
across a particular Class. This means that you cannot save an
object where a previously committed object has the same field value for
fields marked as unique.
A Unique Constraint is checked at commit-time and a constraint
violation will cause a UniqueFieldValueConstraintViolationException to
be thrown. Multiple constraints can be defined on the same class if
required.
How to Use Unique Constraints
// First, you should always index a field you wish to be unique:
config.objectClass(Item.class).objectField("_str").indexed(true);
// Second, add the constraint:
config.add(new UniqueFieldValueConstraint(Item.class, "_str"));
// open objectContainer
try {
// do some work and save some objects
objectContainer.commit();
} catch(UniqueFieldValueConstraintViolationException exc) {
objectContainer.rollback();
}
Unique Constraints are based on commit-time callbacks, also a new
feature in version 6.2, which allow users to listen for commit-time
events. The Unique Constraints use the "on committing" event to verify
that the fields are unique before the final commit is actually
executed.
Unique Constraints are available as of db4o version 6.2.