mybatis handles enumeration types

MyBatis supports persistent enum type properties. Suppose that there is a column of gender type varchar2(10) in the t Uuser table, which stores two values: MALE or FEMALE. In addition, the User object has a gender attribute of enum type, as follows:

public enum Gender { 
MALE,FEMALE; 
}

 

By default, MyBatis uses EnumTypeHandler to handle Java properties of enum type and stores them as the name of enum value. We don't need any additional configuration for this. The enum type property can be used just like the basic data type property, as follows:

create table t_user(
          id number primary key,
          name varchar2(50),
          gender varchar2(10)
);

 

public class User{ 
            private Integer id; 
            private String name; 
            private Gender gender; 

            //setters and getters 
} 

Mapping file:

<insert id="insertUser" parameterType="User"> 
    <selectKey keyProperty="id" resultType="int" order="BEFORE">
        select my_seq.nextval from dual
    </selectKey>
    insert into t_user(id,name,gender) 
    values(#{id},#{name},#{gender}) 
</insert>

Mapping interface:

public interface XxxxMapper{
    int insertUser(User user);    
}

Test method:

@Test
public void test_insertUser(){

SqlSession sqlSession = null;
try {
sqlSession = MyBatisSqlSessionFactory.openSession();

SpecialMapper mapper = sqlSession.getMapper(SpecialMapper.class);
User user = new User("tom",Gender.MALE);

mapper.insertUser(user);

sqlSession.commit();
} catch (Exception e) {
e.printStackTrace();
}
}

 

When the insert student statement is executed, MyBatis takes the name of the gender enumeration (FEMALE/MALE) and stores it in the gender column.

If you want to store the file with 0 and 1 to the gender column, you need to configure a special type processor in the mybatis-config.xml file and specify which enumeration type it deals with.
<typeHandler handler="org.apache.ibatis.type.EnumOrdinalTypeHandler" javaType="com.briup.special.Gender"/>

EnumOrdinalTypeHandler this is a type processor. There is a set method in the source code to help us store values. The source code is as follows

/**
 *    Copyright 2009-2017 the original author or authors.
 *
 *    Licensed under the Apache License, Version 2.0 (the "License");
 *    you may not use this file except in compliance with the License.
 *    You may obtain a copy of the License at
 *
 *       http://www.apache.org/licenses/LICENSE-2.0
 *
 *    Unless required by applicable law or agreed to in writing, software
 *    distributed under the License is distributed on an "AS IS" BASIS,
 *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *    See the License for the specific language governing permissions and
 *    limitations under the License.
 */
package org.apache.ibatis.type;

import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

/**
 * @author Clinton Begin
 */
public class EnumOrdinalTypeHandler<E extends Enum<E>> extends BaseTypeHandler<E> {

  private final Class<E> type;
  private final E[] enums;

  public EnumOrdinalTypeHandler(Class<E> type) {
    if (type == null) {
      throw new IllegalArgumentException("Type argument cannot be null");
    }
    this.type = type;
    this.enums = type.getEnumConstants();
    if (this.enums == null) {
      throw new IllegalArgumentException(type.getSimpleName() + " does not represent an enum type.");
    }
  }

  @Override
  public void setNonNullParameter(PreparedStatement ps, int i, E parameter, JdbcType jdbcType) throws SQLException {
    ps.setInt(i, parameter.ordinal());
  }

  @Override
  public E getNullableResult(ResultSet rs, String columnName) throws SQLException {
    int i = rs.getInt(columnName);
    if (rs.wasNull()) {
      return null;
    } else {
      try {
        return enums[i];
      } catch (Exception ex) {
        throw new IllegalArgumentException("Cannot convert " + i + " to " + type.getSimpleName() + " by ordinal value.", ex);
      }
    }
  }

  @Override
  public E getNullableResult(ResultSet rs, int columnIndex) throws SQLException {
    int i = rs.getInt(columnIndex);
    if (rs.wasNull()) {
      return null;
    } else {
      try {
        return enums[i];
      } catch (Exception ex) {
        throw new IllegalArgumentException("Cannot convert " + i + " to " + type.getSimpleName() + " by ordinal value.", ex);
      }
    }
  }

  @Override
  public E getNullableResult(CallableStatement cs, int columnIndex) throws SQLException {
    int i = cs.getInt(columnIndex);
    if (cs.wasNull()) {
      return null;
    } else {
      try {
        return enums[i];
      } catch (Exception ex) {
        throw new IllegalArgumentException("Cannot convert " + i + " to " + type.getSimpleName() + " by ordinal value.", ex);
      }
    }
  }
  
}

The order value of enumeration type is assigned according to the declaration order in enum. If the declaration order of the objects in the Gender is changed, the data stored in the database does not match the order value.

Keywords: Java Mybatis Apache SQL

Added by DevilsAdvocate on Thu, 17 Oct 2019 01:37:01 +0300