PostgreSql数组及JSON类型数据在Mybatis项目中的使用


postgresql提供了很多数据类型,某些特殊的类型无法同java数据类型映射。Mybatis提供了一些默认的TypeHandler,但不包含诸如数组、json这些类型在内。为了使用pgsql的这些类型,我们可以自己添加一些特定的typehandler,注册后就可以标注使用了。

基本操作流程如下:

1、定义实体类,继承BaseTypeHandler
  
2、在映射文件当中指明typeHandler是这个实体类
  
3、字符赋值为JSONObject类型

实体类代码块:

package com.techen.ami.hes.jobserver.entity;

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

import com.alibaba.fastjson.JSON;
import org.apache.ibatis.type.BaseTypeHandler;
import org.apache.ibatis.type.JdbcType;
import org.postgresql.util.PGobject;

/**
 * @description: postgresql提供了很多数据类型,某些特殊的类型无法同java数据类型映射。Mybatis提供了一些默认的TypeHandler,但不包含诸如数组、json这些类型在内。为了使用pgsql的这些类型,我们可以自己添加一些特定的typehandler,注册后就可以标注使用了。
 * @author: bozhiqiang
 * @updateTime: 2022/7/12 17:07
 * @Param: 
 * @return: 
 * @throw:
 */
public class JsonTypeHandler extends BaseTypeHandler<Object> {

    private static final PGobject pgObject = new PGobject();

    @Override
    public Object getNullableResult(ResultSet resultSet, String columnLabel) throws SQLException {
        return resultSet.getString(columnLabel);
    }

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

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

    @Override
    public void setNonNullParameter(PreparedStatement preparedStatement, int i, Object object, JdbcType jdbcType) throws SQLException {
        pgObject.setType("json");
        pgObject.setValue(JSON.toJSONString(object));
        preparedStatement.setObject(i, pgObject);
    }
}

JSONObject类型数据

image-20220712214436903

映射文件

image-20220712214502296


文章作者: superzqbo
版权声明: 本博客所有文章除特別声明外,均采用 CC BY 4.0 许可协议。转载请注明来源 superzqbo !
评论