golang-gorm框架支持mysql json类型

时间:2025-02-28 07:44:55

gorm框架目前不支持Json类型的数据结构 /

如在Mysql中定义了如下的表结构

CREATE TABLE `report` (
  `id` bigint(20) NOT NULL,
  `query_param` json NOT NULL,
  `create_by` varchar(50) DEFAULT NULL COMMENT '创建人',
  `create_date` timestamp NULL DEFAULT NULL COMMENT '创建时间',
  `update_by` varchar(50) DEFAULT NULL COMMENT '修改人',
  `update_date` timestamp NULL DEFAULT NULL COMMENT '修改时间',
  PRIMARY KEY (`id`),
  UNIQUE KEY `id_UNIQUE` (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4

 

解决办法是自定义一个JSON类型

package models

import (
    "bytes"
    "errors"
    "database/sql/driver"
)
type JSON []byte
func (j JSON) Value() (, error) {
    if () {
        return nil, nil
    }
    return string(j), nil
}
func (j *JSON) Scan(value interface{}) error {
    if value == nil {
        *j = nil
        return nil
    }
    s, ok := value.([]byte)
    if !ok {
        ("Invalid Scan Source")
    }
    *j = append((*j)[0:0], s...)
    return nil
}
func (m JSON) MarshalJSON() ([]byte, error) {
    if m == nil {
        return []byte("null"), nil
    }
    return m, nil
}
func (m *JSON) UnmarshalJSON(data []byte) error {
    if m == nil {
        return ("null point exception")
    }
    *m = append((*m)[0:0], data...)
    return nil
}
func (j JSON) IsNull() bool {
    return len(j) == 0 || string(j) == "null"
}
func (j JSON) Equals(j1 JSON) bool {
    return ([]byte(j), []byte(j1))
}

 

使用如下可以完美支持

type Report struct {
    ID            int64        `json:"id"`
    QueryParam  JSON      `json:"queryParam"`
    CreateBy     string         `json:"createBy"`
    CreateDate        `json:"createDate"`
    UpdateBy     string         `json:"updateBy"`
    UpdateDate        `json:"updateDate"`
}

 

相关文章