Search code examples
mybatisspring-mybatis

Way to enforce length check constraint in MyBatis


I have some check constraints defined by SYS schema in DB for a particular column. Now, while invoking it from Java code through MyBatis, is there anyway to enforce corresponding field length validations through MYBatis configuration only.

PS: I don't want to enforce constraints at VO level (setter individually). Or using JSR 303

DataBase : Oracle 11g Using MyBatis


Solution

  • If you do not want to validate in your java beans (manually, or using JSR 303) I think you could write your own typeHandler for those field.

    Typehandler would handle String fields and do validation. See code example for String TypeHandler. You could enforce your validation logic (of any complexity) in handler's get/set methods.

    If you want to use TypeHandler to trim string to given length when saving to database, do it in setNonNullParameter method.

    Sample code below

        @MappedJdbcTypes(JdbcType.VARCHAR)
       public class ExampleTypeHandler extends BaseTypeHandler<String> {
        @Override
          public void setNonNullParameter(PreparedStatement ps, int i, 
    String parameter, JdbcType jdbcType) throws SQLException {
            ps.setString(i, parameter.substring(0,DESIRED_MAX_LENGTH));
          }
    

    You could also trim (or otherwise modify) values you read from database- you need to modify get* method in your TypeHandler implementation to do that.

    You must tell mappers to use your handler. Otherwise, default handler for given type will be used. Your SQLs in XML file must use syntax

    #{age,javaType=int,jdbcType=NUMERIC,typeHandler=MyTypeHandler}
    

    Check https://mybatis.github.io/mybatis-3/sqlmap-xml.html for details.