Unique Constraints Example

Let's look at a simple example with 2 clients adding objects of the same class to the database. First of all, let's create an appropriate configuration:

UniqueConstraintExample.java: configure
1private static Configuration configure() { 2 Configuration configuration = Db4o.newConfiguration(); 3 configuration.objectClass(Pilot.class).objectField("name") 4 .indexed(true); 5 configuration.add(new UniqueFieldValueConstraint(Pilot.class, 6 "name")); 7 return configuration; 8 }

Configuration returned by configure method will be passed to the server.

UniqueConstraintExample.java: storeObjects
01private static void storeObjects() { 02 new File(FILENAME).delete(); 03 ObjectServer server = Db4o.openServer(configure(), FILENAME, 04 0); 05 Pilot pilot1 = null; 06 Pilot pilot2 = null; 07 try { 08 ObjectContainer client1 = server.openClient(); 09 try { 10 // creating and storing pilot1 to the database 11 pilot1 = new Pilot("Rubens Barichello", 99); 12 client1.set(pilot1); 13 ObjectContainer client2 = server.openClient(); 14 try { 15 // creating and storing pilot2 to the database 16 pilot2 = new Pilot("Rubens Barichello", 100); 17 client2.set(pilot2); 18 // commit the changes 19 client2.commit(); 20 } catch (UniqueFieldValueConstraintViolationException ex) { 21 System.out 22 .println("Unique constraint violation in client2 saving: " 23 + pilot2); 24 client2.rollback(); 25 } finally { 26 client2.close(); 27 } 28 // Pilot Rubens Barichello is already in the database, 29 // commit will fail 30 client1.commit(); 31 } catch (UniqueFieldValueConstraintViolationException ex) { 32 System.out 33 .println("Unique constraint violation in client1 saving: " 34 + pilot1); 35 client1.rollback(); 36 } finally { 37 client1.close(); 38 } 39 } finally { 40 server.close(); 41 } 42 }
Running this example you will get an exception trying to commit client1 as the changes made by client2 containing a Pilot object with the same name are already committed to the database.