Use custom Typehandler in MyBatis to work with JSON type fields in PostgreSQL

Source: Internet
Author: User
Tags mongodb postgresql redis uuid



Business extension fields are often stored in the PostgreSQL database using JSON-formatted data, whereas MyBatis defaults to Typehandler that do not implement JSON-type fields, so we typically need to customize the Typehandler of MyBatis.



The following is a simple implementation of the Typehandler for the JSON type field in MyBatis:


 
 
import org.apache.ibatis.type.BaseTypeHandler;
import org.apache.ibatis.type.JdbcType;
import org.apache.ibatis.type.MappedTypes;
import org.postgresql.util.PGobject;

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


@MappedTypes({Object.class})
public class JsonTypeHandler extends BaseTypeHandler<Object> {

    private static final PGobject jsonObject = new PGobject();

    @Override
    public void setNonNullParameter(PreparedStatement preparedStatement, int i, Object o, JdbcType jdbcType) throws
            SQLException {
        jsonObject.setType("json");
        jsonObject.setValue(JsonUtil.toJsonString(o));
        preparedStatement.setObject(i, jsonObject);

    }

    @Override
    public Object getNullableResult(ResultSet resultSet, String s) throws SQLException {
        return JsonUtil.fromJson(resultSet.getString(s), Object.class);
    }

    @Override
    public Object getNullableResult(ResultSet resultSet, int i) throws SQLException {
        return JsonUtil.fromJson(resultSet.getString(i), Object.class);
    }

    @Override
    public Object getNullableResult(CallableStatement callableStatement, int i) throws SQLException {
        return JsonUtil.fromJson(callableStatement.getString(i), Object.class);
    }
}
}

In addition to writing Typehandler, the following configuration is required in the XML mapping file:


 <resultMap id="BaseResultMap" type="com.test.entity.EventLog">
        <id column="uuid" jdbcType="VARCHAR" property="uuid"/>
        <result column="payload" jdbcType="OTHER" property="payload" typeHandler="com.test.dao.typehandler.JsonTypeHandler"/>
    </resultMap>
    <insert id="insert" parameterType="com.test.entity.EventLog">
        insert into "test".event_log (uuid,payload)
        values (#{uuid,jdbcType=VARCHAR},#{payload,jdbcType=OTHER,typeHandler=com.test.dao.typehandler.JsonTypeHandler})
    </insert>


When used, the object can be converted to a JSON string and then to the corresponding object, as follows:


        EventLogPayload eventLogPayload = JsonUtil.parser(JsonUtil.toJson(eventLog.getPayload()), EventLogPayload.class);


Use custom Typehandler in MyBatis to work with JSON type fields in PostgreSQL


Alibaba Cloud Hot Products

Elastic Compute Service (ECS) Dedicated Host (DDH) ApsaraDB RDS for MySQL (RDS) ApsaraDB for PolarDB(PolarDB) AnalyticDB for PostgreSQL (ADB for PG)
AnalyticDB for MySQL(ADB for MySQL) Data Transmission Service (DTS) Server Load Balancer (SLB) Global Accelerator (GA) Cloud Enterprise Network (CEN)
Object Storage Service (OSS) Content Delivery Network (CDN) Short Message Service (SMS) Container Service for Kubernetes (ACK) Data Lake Analytics (DLA)

ApsaraDB for Redis (Redis)

ApsaraDB for MongoDB (MongoDB) NAT Gateway VPN Gateway Cloud Firewall
Anti-DDoS Web Application Firewall (WAF) Log Service DataWorks MaxCompute
Elastic MapReduce (EMR) Elasticsearch

Alibaba Cloud Free Trail

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.