*
* @since 1.1
*/
protected void validateForSave(ValidationResult validationResult) {
ObjEntity objEntity = getObjectContext()
.getEntityResolver()
.lookupObjEntity(this);
if (objEntity == null) {
throw new CayenneRuntimeException(
"No ObjEntity mapping found for DataObject " + getClass().getName());
}
// validate mandatory attributes
// handling a special case - meaningful mandatory FK... defer failures until
// relationship validation is done... This is just a temporary solution, as
// handling meaningful keys within the object lifecycle requires something more,
// namely read/write methods for relationships and direct values should be
// synchronous with each other..
Map<String, ValidationFailure> failedDbAttributes = null;
for (Object next : objEntity.getAttributes()) {
// TODO: andrus, 2/20/2007 - handle embedded attribute
if (next instanceof EmbeddedAttribute) {
continue;
}
ObjAttribute objAttribute = (ObjAttribute) next;
DbAttribute dbAttribute = objAttribute.getDbAttribute();
if (dbAttribute == null) {
throw new CayenneRuntimeException("ObjAttribute '"
+ objAttribute.getName()
+ "' does not have a corresponding DbAttribute");
}
// pk may still be generated
if (dbAttribute.isPrimaryKey()) {
continue;
}
Object value = this.readPropertyDirectly(objAttribute.getName());
if (dbAttribute.isMandatory()) {
ValidationFailure failure = BeanValidationFailure.validateNotNull(
this,
objAttribute.getName(),
value);
if (failure != null) {
if (failedDbAttributes == null) {
failedDbAttributes = new HashMap<String, ValidationFailure>();
}
failedDbAttributes.put(dbAttribute.getName(), failure);
continue;
}
}
// validate length
if (value != null && dbAttribute.getMaxLength() > 0) {
if (value.getClass().isArray()) {
int len = Array.getLength(value);
if (len > dbAttribute.getMaxLength()) {
String message = "\""
+ objAttribute.getName()
+ "\" exceeds maximum allowed length ("
+ dbAttribute.getMaxLength()
+ " bytes): "
+ len;
validationResult.addFailure(new BeanValidationFailure(
this,
objAttribute.getName(),
message));
}
}
else if (value instanceof CharSequence) {
int len = ((CharSequence) value).length();
if (len > dbAttribute.getMaxLength()) {
String message = "\""
+ objAttribute.getName()
+ "\" exceeds maximum allowed length ("
+ dbAttribute.getMaxLength()
+ " chars): "
+ len;
validationResult.addFailure(new BeanValidationFailure(
this,
objAttribute.getName(),
message));
}
}
}
}
// validate mandatory relationships
for (final ObjRelationship relationship : objEntity.getRelationships()) {
if (relationship.isSourceIndependentFromTargetChange()) {
continue;
}