Application Skills of Mybatis Custom Type Converter

  • 2021-07-22 09:49:48
  • OfStack

1 Under normal circumstances, mybatis's own type converter is enough, but the demand is endless. Custom type converter is still learning 1, and it will be used someday.

Give a useless example

javabean is as follows:


public class User {
  private Integer id;
  private Message message;
}

public class Message {
  private Integer id;
  private String address;
  private String job;
}

The database User table is as follows:

列名 类型
id int
message varchar

The Message object is an bean in java and a string in the database, which requires type conversion 1, so my purpose is:

Through the custom type converter, the message object is automatically converted into string type when the stored data is obtained, and stored in the database. When fetching data, the string is automatically converted into an Message object and encapsulated into the result set.

Type converter:


@MappedTypes(Message.class)
@MappedJdbcTypes(JdbcType.VARCHAR)
public class MessageTypeHandler implements TypeHandler<Message> {
  @Override
  public void setParameter(PreparedStatement ps, int i, Message parameter, JdbcType jdbcType) throws SQLException {
    ps.setString(i, JSON.toJSONString(parameter));
  }

  @Override
  public Message getResult(ResultSet rs, String columnName) throws SQLException {
    return JSON.parseObject(rs.getString(columnName),Message.class);
  }

  @Override
  public Message getResult(ResultSet rs, int columnIndex) throws SQLException {
    return JSON.parseObject(rs.getString(columnIndex),Message.class);
  }

  @Override
  public Message getResult(CallableStatement cs, int columnIndex) throws SQLException {
    return null;
  }
}

Add the following configuration to the mybatis configuration file:


  <typeHandlers>
    <typeHandler handler="org.mybatis.***.MessageTypeHandler"/>
  </typeHandlers>

In this way, we can write sql directly without manually handling the type conversion.


  <insert id="insertUser">
      insert into user (id,message) values (#{id},#{message})
  </insert>

  <select id="getUser" parameterType="int" resultType="org.mybatis.***.mapper.User" >
    select id,message from user where id = #{id}
  </select>


Related articles: