Uploaded image for project: 'iBatis for Java [READ ONLY]'
  1. iBatis for Java [READ ONLY]
  2. IBATIS-749

Base class for enum TypeHandlers using orginal value for persistence

    XMLWordPrintableJSON

Details

    • New Feature
    • Status: Open
    • Major
    • Resolution: Unresolved
    • 3.0 Beta 9
    • None
    • Core
    • None

    Description

      In some cases it would be useful to have base class for enum TypeHandlers, that allow to store enumerations to the database by their ordinal() value. Code might look like this:

      /**

      • This class converts enumeration type into the database form by ordinal value (and back again).
        */
        public abstract class EnumOrdinalTypeHandler extends BaseTypeHandler {
        private final Class type;
        private final Method values;

      protected EnumOrdinalTypeHandler(Class type) {
      this.type = type;
      try

      { this.values = type.getDeclaredMethod("values"); }

      catch(Exception ex)

      { throw new IllegalArgumentException("Class " + type.getSimpleName() + " is not an enumeration class.", ex); }

      }

      @Override
      public void setNonNullParameter(PreparedStatement ps, int i, Object parameter, JdbcType jdbcType) throws SQLException

      { ps.setInt(i, ((Enum)parameter).ordinal()); }

      @Override
      public Object getNullableResult(ResultSet rs, String columnName) throws SQLException {
      int i = rs.getInt(columnName);
      if(rs.wasNull())

      { return null; } else {
      try { Object[] enums = (Object[])values.invoke(null); return enums[i]; } catch (Exception ex) { throw new IllegalArgumentException( "Cannot convert " + i + " to " + type.getSimpleName() + " by ordinal value.", ex ); }
      }
      }

      @Override
      public Object getNullableResult(CallableStatement cs, int columnIndex) throws SQLException {
      int i = cs.getInt(columnIndex);
      if(cs.wasNull()) { return null; }

      else {
      try

      { Object[] enums = (Object[])values.invoke(null); return enums[i]; }

      catch (Exception ex)

      { throw new IllegalArgumentException( "Cannot convert " + i + " to " + type.getSimpleName() + " by ordinal value.", ex ); }

      }
      }

      }

      Code is tested and functional.

      Attachments

        Activity

          People

            Unassigned Unassigned
            novoj Jan Novotný
            Votes:
            0 Vote for this issue
            Watchers:
            0 Start watching this issue

            Dates

              Created:
              Updated: