mybatis handle enumerated types

MyBatis supports persistent enum type properties. Suppose t_user table has a gender (Sex) type (10), two kinds of values ​​stored FEMALE or MALE varchar2. And, the User object has a gender enum type properties as follows:

public enum Gender { 
MALE,FEMALE; 
}

 

MyBatis using default EnumTypeHandler treated enum type Java properties, and stores the name of the enum value. For this reason we do not need to do any additional configuration. Can be used as basic data type attribute enum type attribute used 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);    
}

testing 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 name when the statement is executed insertStudent MyBatis will take Gender enumeration (FEMALE / MALE), and stored in the GENDER column.

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

EnumOrdinalTypeHandler This is the type of processor, the source code is to have a set value in helping us keep source code 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);
      }
    }
  }
  
}

Enumerated type [order] is based on the value of the order enum declaration of assignment. If you change the order of declaration Gender inside the object, the data stored in the database and will not match the value in this order.

Guess you like

Origin www.cnblogs.com/Magic-Li/p/11684218.html