前言
将第三方 API 数据持久化到数据库是后端开发中的常见场景。本文以百度天气接口为例,演示如何利用 MybatisPlus 框架将获取到的 JSON 数据高效、准确地存入 PostgreSQL 数据库。重点涵盖数据库表结构设计、实体类映射配置以及 Service 层的事务处理逻辑。

一、PostgreSQL 数据库设计
PostgreSQL 在处理复杂查询和扩展性方面表现优异。针对百度天气返回的数据结构,我们设计了五张物理表来分别存储实时信息、警报、指数及预报数据。
1. 模型设计思路
根据接口文档的业务维度,我们将数据拆分为核心表与关联表。实时天气为主表,其他如预警、指数、预报等通过外键关联。这种设计既保证了查询效率,也便于后续维护。

2. 建表语句实现
以下是具体的 DDL 语句。注意温度、湿度等字段采用了 DECIMAL(8,2) 类型,而非 INT,这是为了兼容可能出现的浮点数精度问题。
实时天气信息表:
create table biz_weather_now (
pk_id INT8 not null,
location_code VARCHAR(6) not null default '',
temp DECIMAL(8,2) not null default 999999,
feels_like DECIMAL(8,2) not null default 999999,
rh DECIMAL(8,2) not null default 999999,
wind_class VARCHAR(10) null,
wind_dir () ,
text () ,
prec_1h (,) ,
clouds (,) ,
vis (,) ,
aqi (,) ,
pm25 (,) ,
pm10 (,) ,
no2 (,) ,
so2 (,) ,
o3 (,) ,
co (,) ,
uptime ,
PK_BIZ_WEATHER_NOW (pk_id)
);
comment biz_weather_now ;
comment biz_weather_now.pk_id ;
comment biz_weather_now.location_code ;
comment biz_weather_now.temp ;
comment biz_weather_now.feels_like ;
comment biz_weather_now.rh ;
comment biz_weather_now.wind_class ;
comment biz_weather_now.wind_dir ;
comment biz_weather_now.text ;
comment biz_weather_now.prec_1h ;
comment biz_weather_now.clouds ;
comment biz_weather_now.vis ;
comment biz_weather_now.aqi ;
comment biz_weather_now.pm25 ;
comment biz_weather_now.pm10 ;
comment biz_weather_now.no2 ;
comment biz_weather_now.so2 ;
comment biz_weather_now.o3 ;
comment biz_weather_now.co ;
comment biz_weather_now.uptime ;







