By default db4o doesn't support any validation and integrity checks except unique field values. However you can use .NET data annotations to validate objects. The .NET data annotations provide attributes for validating objects.However you can use other libraries like Hibernate-Validator to validate objects. Download the library from the official Hibernate site and include into your project.Objects can be validated when you store them in the database by using db4o events.
Add the Annotation to your classes which you want to validate:
Now we can write a validation method and register it to the db4o events:
private static class ValidationListener implements EventListener4<CancellableObjectEventArgs> { private final Validator validator = Validation.buildDefaultValidatorFactory() .getValidator(); @Override public void onEvent(Event4<CancellableObjectEventArgs> events, CancellableObjectEventArgs eventInfo) { Set<ConstraintViolation<Object>> violations = validator.validate(eventInfo.object()); if (!violations.isEmpty()) { throw new ValidationException(buildMessage(violations)); } } private String buildMessage(Set<ConstraintViolation<Object>> violations) { final StringBuilder builder = new StringBuilder("Violations of validation-rules:\n"); for (ConstraintViolation<Object> violation : violations) { builder.append(violation.getPropertyPath()).append(" ") .append(violation.getMessage()).append("\n"); } return builder.toString(); } }
EventRegistry events = EventRegistryFactory.forObjectContainer(container); events.creating().addListener(new ValidationListener()); events.updating().addListener(new ValidationListener());
After that you can store and update objects. In case a object violates its validation rules an exception is thrown. That exception will contain information about the violations.
Pilot pilot = new Pilot("Joe"); container.store(pilot);
Pilot otherPilot = new Pilot(""); try { container.store(otherPilot); } catch (EventException e) { ValidationException cause = (ValidationException) e.getCause(); System.out.println(cause.getMessage()); }