views:

100

answers:

2

What is the correct way to defend against trying to store more text than can be accommodated in a VARCHAR2 database field?

Say the PARTNER_ROLE field of the REGISTRATIONS table is declared as VARCHAR2(80).

This field is mapped in the Registration class in Java as

public class Registration {
  @Column(name=”PARTNER_ROLE” length=”80”)
  private String partnerRole;
}

However, the setPartnerRole() method allows the user to stuff a string of any length. The problem is encountered only when one subsequently tries to insert or update the REGISTRATIONS record. Oracle complains.

What is the correct way to handle this situation?

A: 

Solution 1 : In UI side itself set the field length limit in text-field or text-area that takes input for PARTNER_ROLE. A javascript check also could be done.

Solution 2 : a bit lousy solution. Check in DB side using java.sql.DatabaseMetaData class. Not good one if need to check for multiple fields multiple-times.

java.sql.DatabaseMetaData class gives data about the table like column_size,type_name etc. For ex :

 ResultSet rsColumns = null;
    DatabaseMetaData meta = conn.getMetaData();
    rsColumns = meta.getColumns(null, null, "aTableName", null);

where aTableName is one that is to be studied. Check the input value length with column_size of that particular tableName.columnName.

Abi
A: 

You can use JSR-303 Bean Validation annotations to annotate the field with the maximum length and then you can use a validator to check those annotations are met, e.g. when the setter is called. This can also be used to give you meaningful error messages automatically.

public class Registration {
  @Size(max = 80)
  @Column(name=”PARTNER_ROLE” length=”80”)
  private String partnerRole;

  // you need to get this from somewhere, but this depends on your environment
  private ValidatorFactory validatorFactory;

  public Set<ConstraintViolation<Registration>> validate() {
    Validator validator = validatorFactory.getValidator();
    return validator.<Registration>validate(this);
  }
}
Thomas Lötzer
Very nice! Thank you very much.
Sri Sankaran