mysql JSON用法 mybatis当字符串怎么弄
MySQL中JSON的用法:
- 创建表时指定列为JSON类型:
CREATE TABLE `my_table` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`json_data` json DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
- 插入JSON数据:
INSERT INTO `my_table` (`json_data`) VALUES ('{"name": "Tom", "age": 20}');
- 查询JSON数据:
SELECT json_data->"$.name" AS name, json_data->"$.age" AS age FROM `my_table`;
Mybatis中将JSON数据作为字符串处理时,可以使用以下方式:
- 在Mapper接口中定义对应的方法:
@Select("SELECT json_data FROM my_table WHERE id = #{id}")
String getJsonDataById(int id);
- 在SqlMapConfig.xml中配置类型别名:
<typeAliases>
<typeAlias type="java.lang.String" alias="json"/>
</typeAliases>
- 在Mapper接口中定义对应的方法,使用@ResultType指定返回值类型:
@Select("SELECT json_data FROM my_table WHERE id = #{id}")
@ResultType(json.class)
String getJsonDataById(int id);
原文地址: https://www.cveoy.top/t/topic/bmvU 著作权归作者所有。请勿转载和采集!