【PostgreSQL】MyBatis中自定义typeHandler映射PostgreSQL中json类型字段

 

数据库PostgreSQL,表sub_rule的detail字段类型为json

【PostgreSQL】MyBatis中自定义typeHandler映射PostgreSQL中json类型字段_第1张图片

实体类中detail字段类型为Object

public class SubRule {
    private String id;
    private String name;
    private Object detail;             //json类型
    private String ruleId;
    private int dimensionSize;

}

正常来说,MyBatis的mapper中是无法映射json类型数据的,因为我们需要自定义一个typeHandler,继承BaseTypeHandler。

package com.yealink.ptms.typeHandler;

import com.yealink.ptms.util.JsonUtil;
import org.apache.ibatis.type.BaseTypeHandler;
import org.apache.ibatis.type.JdbcType;
import org.apache.ibatis.type.MappedTypes;
import org.codehaus.jackson.map.ObjectMapper;
import org.postgresql.util.PGobject;

import java.io.IOException;
import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

/**
 * Created by yl1794 on 2018/8/21.
 */
@MappedTypes(Object.class)
public class JSONTypeHandlerPg extends BaseTypeHandler {
    private static final PGobject jsonObject = new PGobject();

    @Override
    public void setNonNullParameter(PreparedStatement ps, int i, Object parameter, JdbcType jdbcType) throws SQLException {
        jsonObject.setType("json");
        try {
            jsonObject.setValue(new ObjectMapper().writeValueAsString(parameter));  //java对象转化成json字符串
        } catch (IOException e) {
            e.printStackTrace();
        }
        ps.setObject(i, jsonObject);
    }

    @Override
    public Object getNullableResult(ResultSet rs, String columnName) throws SQLException {
        return rs.getString(columnName);                                 // 返回String
    }

    @Override
    public Object getNullableResult(ResultSet rs, int columnIndex) throws SQLException {
        return rs.getString(columnIndex);
    }

    @Override
    public Object getNullableResult(CallableStatement cs, int columnIndex) throws SQLException {
        return cs.getString(columnIndex);
    }

}
 
  

在mapper中需要类型转换的地方引入即可

INSERT INTO sub_rule (id, name, detail, dimension_size, rule_id)
        VALUES (
            #{id, jdbcType=VARCHAR},
            #{name, jdbcType=VARCHAR},
            #{detail, jdbcType=OTHER, typeHandler=com.yealink.ptms.typeHandler.JSONTypeHandlerPg},
            #{dimensionSize, jdbcType=INTEGER},
            #{ruleId, jdbcType=VARCHAR}
        )

以插入为例,服务中方法大致如下,需要注意的是,detail的值需尽量是json格式的(一般用map),这样才可以存到数据库中时也是json格式的。

    public void add(SubRule subRule) {
        subRule.setId(UUIDUtil.randomUUID());
        subRule.setName("设计2");
        subRule.setRuleId("2");
        subRule.setDimensionSize(3);

        Map detail = new HashMap<>();
        detail.put("1", new String[] {"2"});
        detail.put("3", new String[] {"6","8"});

        subRule.setDetail(detail);
        indexMapper.add(subRule);
    }

 

 

 

 

你可能感兴趣的:(数据库)