r.r
r.r

Reputation: 255

Mybatis inline type handler for select statements

there is simple select

<select id = "getWidgetConfig" resultType="com.comp.entity.widgets.cnfg.Widget">
    SELECT `json_config`
    FROM   `widget_config`
    WHERE  `widget_id` = #{widgetId} 
</select>

where json_config is string value.

Can i bind type/result handler(inline) to convert json_config value into my entity Widget using my handler?

I can do this inline for update/insert statements

INSERT INTO `widget_config` 
    (
        `json_config`
    ) 
VALUES 
    ( 
        #{widget,typeHandler=com.comp.mybatis.handlers.widget.WidgetTypeHandler} 
    )

How can i do similar for select statements? Thanks

Upvotes: 0

Views: 2197

Answers (1)

I don't think it is possible to use type handlers on the top level in select. But you can approach this a bit by using result map with constructor:

<resultMap id="widgetMap" type="Widget">
  <constructor>
     <arg column="json_config" javaType="string"/>
  </constructor>
</resultMap>

<select id="getWidgetConfig" resultMap="widgetMap">
   SELECT `json_config`
    FROM   `widget_config`
    WHERE  `widget_id` = #{widgetId} 
</select>

The potential downside is that you need to have parsing logic in constructor of Widget. If this not an option one way to overcome this is to create copy constructor for Widget and change mapping like this:

<resultMap id="widgetMap" type="Widget">
  <constructor>
     <arg column="json_config" javaHandler="com.comp.mybatis.handlers.widget.WidgetTypeHandler"/>
  </constructor>
</resultMap>

You need make sure Widget has appropriate copy constructor that takes value of type Widget and creates a copy (it may probably reuse internals of the passed Widget if they are immutable).

Upvotes: 1

Related Questions