自学内容网 自学内容网

将JSON的格式数据存储到数据库中

将JSON的格式数据存储到数据库中,在一些业务中需要存储一个设备的一些属性。比如 这样以键值对出现的形式,存储在数据库中。我们可以以JSON的格式存储。

数据库字段设计的时候选择JSON类型的。

对于需要存储的内容用Map集合进行存储

Map<String, Object> jsonData = new HashMap<>();
for (int i = 0; i < attributes.size(); i++) {
    Attribute att = attributes.get(i);
    jsonData.put(att.getAttrKey(),att.getAttrValue());
}

使用FastJson将map转为JSON的字符串。然后插入到数据库中就可以了。

String  json = (String) JSONObject.toJSONString(jsonData);

mapper.xml中的语句

  <insert id="insertBatchRows" parameterType="java.util.List" useGeneratedKeys="true" keyProperty="id">
        insert into tb_voice_raw (device_id, device_type, raw_data_path, status, created_at, voice_name, source,parameters)
        values
        <foreach item="item" index="index" collection="list" separator=",">
            (#{item.deviceId}, #{item.deviceType}, #{item.rawDataPath}, #{item.status}, #{item.createdAt}, #{item.voiceName}, #{item.source},#{item.paramsAsJson})
        </foreach>
    </insert>

原文地址:https://blog.csdn.net/ngczx/article/details/142760207

免责声明:本站文章内容转载自网络资源,如本站内容侵犯了原著者的合法权益,可联系本站删除。更多内容请关注自学内容网(zxcms.com)!