1. 程式人生 > >mybatis typeHandler自定義型別轉換器

mybatis typeHandler自定義型別轉換器

Mybatis預設不支援Calendar
解決辦法:

mybatis提供了對自定義的型別轉換器(typeHandler)的支援,因此我們可以自己編寫型別轉換器來實現這一自動轉換的功能。

實現步驟:

第一步:編寫自定義型別轉換器

public class CalendarTypeHandler implements TypeHandler<Calendar>{

    @Override
    public Calendar getResult(ResultSet rs, String string) throws SQLException{
        Timestamp time = rs.getTimestamp(string
); Calendar c = Calendar.getInstance(); c.setTimeInMillis(time.getTime()); return c; } @Override public Calendar getResult(ResultSet rs, int i) throws SQLException{ Timestamp time = rs.getTimestamp(i); Calendar c = Calendar.getInstance(); c.setTimeInMillis(time.getTime()); return
c; } @Override public Calendar getResult(CallableStatement cs, int i) throws SQLException{ Timestamp time = cs.getTimestamp(i); Calendar c = Calendar.getInstance(); c.setTimeInMillis(time.getTime()); return c; } @Override public void setParameter
(PreparedStatement ps, int i, Calendar t, JdbcType jt) throws SQLException { ps.setTimestamp(i, new Timestamp(t.getTimeInMillis())); } }

第二步:註冊型別轉換器

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration
        PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-config.dtd">

<configuration>

    <typeHandlers>
        <typeHandler handler="com.ndkey.data.mybatis.CalendarTypeHandler" javaType="java.util.Calendar" jdbcType="TIMESTAMP"/>
    </typeHandlers>
</configuration>

第三步: 指定型別轉換

<resultMap id="BaseResultMap" type="com.nington.armstrong.fundamental.Partner" >
    <id column="id" property="id" jdbcType="VARCHAR" />
    <result column="concurrency_version" property="concurrencyVersion" jdbcType="INTEGER" />
    <result column="name" property="name" jdbcType="VARCHAR" />
    <result column="create_time" javaType="java.util.Calendar" property="createTime" jdbcType="TIMESTAMP" />
    <result column="update_time" javaType="java.util.Calendar" property="updateTime" jdbcType="TIMESTAMP" />
    <result column="_deleted" property="deleted" jdbcType="TINYINT" />
  </resultMap>

好了,到此mybatis就能將資料庫中的型別與java中的型別自動做轉換了。