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

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

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

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

java 复制代码
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的字符串。然后插入到数据库中就可以了。

java 复制代码
String  json = (String) JSONObject.toJSONString(jsonData);

mapper.xml中的语句

java 复制代码
  <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>
相关推荐
神王宝宝 王者小学7 小时前
HBase: 看上去很美
大数据·数据库·hbase
io无心8 小时前
Shardingsphere5分库分表
数据库·mysql
wWYy.8 小时前
Mysql:主键索引 唯一索引 普通索引 前缀索引
数据库·mysql
宝杰X79 小时前
Android Room3 多平台数据库
android·数据库
猿长大人12 小时前
C# | JSON 序列化中的多态接口处理:基于 Attribute 实现精准 $type 控制
c#·json
sky_81061312 小时前
Oracle ERP 各模块业务管理功能及底层表说明
数据库·oracle
YMatrix 官方技术社区13 小时前
CittaBase vs. Neo4j :原生图性能实测与混合检索实践
数据库·功能测试·ymatrix
闲猫14 小时前
LangChain / Integrations / Integrations by component / Tool
java·数据库·langchain
xqqxqxxq15 小时前
SQL 连接查询技术笔记
数据库·笔记·sql
消失的旧时光-194315 小时前
第六篇:Redis Hash——一个用户对象应该保存成 JSON,还是保存成 Hash?
redis·json·哈希算法