mybatis自定义类型处理程序,无注释 [英] mybatis custom type handler without annoations

查看:78
本文介绍了mybatis自定义类型处理程序,无注释的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是mybatis的新手.我正在尝试将JDBC整数映射到自定义类.我在此看到的所有示例都使用了注释,是否可以不使用注释,并这样做?任何示例将不胜感激.

I'm new to mybatis. I am trying to map a JDBC integer to a custom class. All the examples that I have seen on this have used annotations, is it possible to not use annotations and do this? Any example would be greatly appreciated.

Sreekanth

Sreekanth

推荐答案

这绝对是可能的,并且在文档的Mapper 部分.

It is definitely possible and is described in general in Configuration and in Mapper sections of the documentation.

首先定义处理程序:

@MappedJdbcTypes(JdbcType.INTEGER)
public class MyClassHandler extends BaseTypeHandler<MyClass> {

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

    @Override
    public MyClass getNullableResult(ResultSet rs, String columnName)
            throws SQLException {
        int val = rs.getInt(columnName);
        if (rs.wasNull())
            return null;
        else
            return MyClass.valueOf(val);
    }

    @Override
    public MyClass getNullableResult(ResultSet rs, int columnIndex)
            throws SQLException {
        int val = rs.getInt(columnIndex);
        if (rs.wasNull())
            return null;
        else
            return MyClass.valueOf(val);
    }

    @Override
    public MyClass getNullableResult(CallableStatement cs, int columnIndex)
            throws SQLException {
        int val = cs.getInt(columnIndex);
        if (cs.wasNull())
            return null;
        else
            return MyClass.valueOf(val);
    }
}

然后在mybatis-config.xml中对其进行配置:

Then configure it in mybatis-config.xml:

<typeHandlers>
    <typeHandler handler="my.company.app.MyClassHandler"/>
</typeHandlers>

现在您可以在xml映射器中使用它. 如果你有课

Now you can use it in xml mappers. If you have a class

class SomeTypeEntity {
    private MyClass myClassField;
};

用于查询resultMap中的字段配置处理程序,如下所示:

For querying the field configure handler in the resultMap like this:

<resultMap id="someMap" type="SomeTypeEntity">
    <result property="myClassField" column="my_class_column" typeHandler="my.company.app.MyClassHandler"/>
</resultMap>

对于insert/update,请像这样使用它:

For insert/update use it like this:

<update id="updateSomeTypeWithMyClassField">
   update some_type
   set
    my_class_column = @{someTypeEntity.myClassField, typeHandler=my.company.app.MyClassHandler},
</update>

对于映射器方法:

void updateSomeTypeWithMyClassField(@Param("someTypeEntity") SomeTypeEntity entity);

这篇关于mybatis自定义类型处理程序,无注释的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆