项目初始化
新建Spring Boot 项目

添加依赖
Spring Boot Web 依赖
XML
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
Spring AI Alibaba 依赖参考官方示例
XML
<dependencyManagement>
<dependencies>
<dependency>
<groupId>com.alibaba.cloud.ai</groupId>
<artifactId>spring-ai-alibaba-bom</artifactId>
<version>1.0.0.2</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>
<dependencies>
<dependency>
<groupId>com.alibaba.cloud.ai</groupId>
<artifactId>spring-ai-alibaba-starter-dashscope</artifactId>
</dependency>
</dependencies>
MySQL
XML
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-jdbc</artifactId>
</dependency>
<!-- MySQL 驱动 -->
<dependency>
<groupId>com.mysql</groupId>
<artifactId>mysql-connector-j</artifactId>
</dependency>
其他依赖
XML
<!-- 工具类 -->
<dependency>
<groupId>cn.hutool</groupId>
<artifactId>hutool-all</artifactId>
<version>5.8.22</version> <!-- 简化字符串、集合操作 -->
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.18.30</version> <!-- 版本可根据项目需求调整 -->
<optional>true</optional>
</dependency>
完整如下
XML
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>3.5.7</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.haoge</groupId>
<artifactId>text-to-sql</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>text-to-sql</name>
<description>通过自然语言描述,生成SQL语句</description>
<url/>
<licenses>
<license/>
</licenses>
<developers>
<developer/>
</developers>
<scm>
<connection/>
<developerConnection/>
<tag/>
<url/>
</scm>
<properties>
<java.version>21</java.version>
</properties>
<dependencyManagement>
<dependencies>
<dependency>
<groupId>com.alibaba.cloud.ai</groupId>
<artifactId>spring-ai-alibaba-bom</artifactId>
<version>1.0.0.2</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>com.alibaba.cloud.ai</groupId>
<artifactId>spring-ai-alibaba-starter-dashscope</artifactId>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.18.30</version> <!-- 版本可根据项目需求调整 -->
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-jdbc</artifactId>
</dependency>
<!-- MySQL 驱动 -->
<dependency>
<groupId>com.mysql</groupId>
<artifactId>mysql-connector-j</artifactId>
</dependency>
<!-- 工具类 -->
<dependency>
<groupId>cn.hutool</groupId>
<artifactId>hutool-all</artifactId>
<version>5.8.22</version> <!-- 简化字符串、集合操作 -->
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<configuration>
<annotationProcessorPaths>
<path>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.18.30</version>
</path>
</annotationProcessorPaths>
</configuration>
</plugin>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<configuration>
<excludes>
<exclude>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
</exclude>
</excludes>
</configuration>
</plugin>
</plugins>
</build>
</project>
配置文件
server:
port: 8080
spring:
application:
name: text-to-sql
profiles:
active: local
Spring AI Alibaba
spring:
ai:
dashscope:
api-key: 申请的API-KEY
测试
参考官方示例代码
java
@RestController
@RequestMapping("/hello/world")
public class HelloWorldController {
private static final String DEFAULT_PROMPT = "你是一个博学的智能聊天助手,请根据用户提问回答!";
private final ChatClient dashScopeChatClient;
public HelloWorldController(ChatClient.Builder chatClientBuilder) {
this.dashScopeChatClient = chatClientBuilder
.defaultSystem(DEFAULT_PROMPT)
// 实现 Logger 的 Advisor
.defaultAdvisors(
new SimpleLoggerAdvisor()
)
// 设置 ChatClient 中 ChatModel 的 Options 参数
.defaultOptions(
DashScopeChatOptions.builder()
.withTopP(0.7)
.build()
)
.build();
}
/**
* ChatClient 简单调用
*/
@GetMapping("/simple/chat")
public String simpleChat(@RequestParam(value = "query", defaultValue = "你好,很高兴认识你,能简单介绍一下自己吗?")String query) {
return dashScopeChatClient.prompt(query).call().content();
}
}
启动项目访问:http://localhost:8080/hello/world/simple/chat

数据库初始化
新建MySQL数据库
sql
create database text_to_sql;
use text_to_sql;
新建表 (AI 生成)
sql
CREATE TABLE IF NOT EXISTS `user` (
`id` BIGINT UNSIGNED NOT NULL AUTO_INCREMENT COMMENT '用户ID(主键)',
`username` VARCHAR(50) NOT NULL COMMENT '用户名',
`password` VARCHAR(100) NOT NULL COMMENT '密码(加密存储,如BCrypt)',
`phone` VARCHAR(11) NOT NULL COMMENT '手机号(唯一)',
`email` VARCHAR(100) DEFAULT NULL COMMENT '邮箱(唯一)',
`avatar` VARCHAR(255) DEFAULT NULL COMMENT '头像URL',
`gender` TINYINT DEFAULT 0 COMMENT '性别(0-未知,1-男,2-女)',
`birth_date` DATE DEFAULT NULL COMMENT '出生日期',
`status` TINYINT NOT NULL DEFAULT 1 COMMENT '状态(0-禁用,1-正常)',
`created_at` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
`updated_at` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间',
PRIMARY KEY (`id`),
UNIQUE KEY `uk_phone` (`phone`),
UNIQUE KEY `uk_email` (`email`),
KEY `idx_username` (`username`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='用户表';
CREATE TABLE IF NOT EXISTS `category` (
`id` BIGINT UNSIGNED NOT NULL AUTO_INCREMENT COMMENT '分类ID(主键)',
`name` VARCHAR(50) NOT NULL COMMENT '分类名称',
`parent_id` BIGINT UNSIGNED DEFAULT 0 COMMENT '父分类ID(0-一级分类)',
`level` TINYINT NOT NULL DEFAULT 1 COMMENT '分类级别(1-一级,2-二级...)',
`sort` INT NOT NULL DEFAULT 0 COMMENT '排序(数字越小越靠前)',
`status` TINYINT NOT NULL DEFAULT 1 COMMENT '状态(0-禁用,1-启用)',
`created_at` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
`updated_at` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间',
PRIMARY KEY (`id`),
KEY `idx_parent_id` (`parent_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='商品分类表';
CREATE TABLE IF NOT EXISTS `product` (
`id` BIGINT UNSIGNED NOT NULL AUTO_INCREMENT COMMENT '商品ID(主键)',
`category_id` BIGINT UNSIGNED NOT NULL COMMENT '分类ID(关联category表)',
`name` VARCHAR(200) NOT NULL COMMENT '商品名称',
`subtitle` VARCHAR(255) DEFAULT NULL COMMENT '商品副标题',
`main_image` VARCHAR(255) NOT NULL COMMENT '主图URL',
`price` DECIMAL(10,2) NOT NULL COMMENT '售价(元)',
`market_price` DECIMAL(10,2) DEFAULT NULL COMMENT '市场价(元)',
`stock` INT NOT NULL DEFAULT 0 COMMENT '库存数量',
`sales` INT NOT NULL DEFAULT 0 COMMENT '销量',
`status` TINYINT NOT NULL DEFAULT 1 COMMENT '状态(0-下架,1-上架)',
`description` TEXT COMMENT '商品详情(富文本)',
`created_at` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
`updated_at` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间',
PRIMARY KEY (`id`),
KEY `idx_category_id` (`category_id`),
KEY `idx_status` (`status`),
KEY `idx_created_at` (`created_at`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='商品表';
CREATE TABLE IF NOT EXISTS `product_image` (
`id` BIGINT UNSIGNED NOT NULL AUTO_INCREMENT COMMENT '图片ID(主键)',
`product_id` BIGINT UNSIGNED NOT NULL COMMENT '商品ID(关联product表)',
`image_url` VARCHAR(255) NOT NULL COMMENT '图片URL',
`sort` INT NOT NULL DEFAULT 0 COMMENT '排序(0-主图,1+详情图)',
`created_at` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
PRIMARY KEY (`id`),
KEY `idx_product_id` (`product_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='商品图片表';
CREATE TABLE IF NOT EXISTS `shipping` (
`id` BIGINT UNSIGNED NOT NULL AUTO_INCREMENT COMMENT '地址ID(主键)',
`user_id` BIGINT UNSIGNED NOT NULL COMMENT '用户ID(关联user表)',
`receiver_name` VARCHAR(50) NOT NULL COMMENT '收货人姓名',
`receiver_phone` VARCHAR(11) NOT NULL COMMENT '收货人手机号',
`province` VARCHAR(20) NOT NULL COMMENT '省份',
`city` VARCHAR(20) NOT NULL COMMENT '城市',
`district` VARCHAR(20) NOT NULL COMMENT '区/县',
`detail_address` VARCHAR(255) NOT NULL COMMENT '详细地址',
`is_default` TINYINT NOT NULL DEFAULT 0 COMMENT '是否默认地址(0-否,1-是)',
`created_at` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
`updated_at` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间',
PRIMARY KEY (`id`),
KEY `idx_user_id` (`user_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='收货地址表';
CREATE TABLE IF NOT EXISTS `order` (
`id` BIGINT UNSIGNED NOT NULL AUTO_INCREMENT COMMENT '订单ID(主键)',
`order_no` VARCHAR(32) NOT NULL COMMENT '订单编号(唯一,如2024052010000001)',
`user_id` BIGINT UNSIGNED NOT NULL COMMENT '用户ID(关联user表)',
`shipping_id` BIGINT UNSIGNED NOT NULL COMMENT '收货地址ID(关联shipping表)',
`total_amount` DECIMAL(10,2) NOT NULL COMMENT '订单总金额(元)',
`pay_amount` DECIMAL(10,2) NOT NULL COMMENT '实付金额(元,含优惠/运费)',
`freight_amount` DECIMAL(10,2) NOT NULL DEFAULT 0.00 COMMENT '运费金额(元)',
`discount_amount` DECIMAL(10,2) NOT NULL DEFAULT 0.00 COMMENT '优惠金额(元)',
`pay_type` TINYINT DEFAULT NULL COMMENT '支付方式(1-支付宝,2-微信,3-银行卡)',
`status` TINYINT NOT NULL COMMENT '订单状态(0-待付款,1-待发货,2-待收货,3-已完成,4-已取消)',
`payment_time` DATETIME DEFAULT NULL COMMENT '支付时间',
`ship_time` DATETIME DEFAULT NULL COMMENT '发货时间',
`receive_time` DATETIME DEFAULT NULL COMMENT '确认收货时间',
`cancel_time` DATETIME DEFAULT NULL COMMENT '取消时间',
`note` VARCHAR(500) DEFAULT NULL COMMENT '订单备注',
`created_at` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
`updated_at` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间',
PRIMARY KEY (`id`),
UNIQUE KEY `uk_order_no` (`order_no`),
KEY `idx_user_id` (`user_id`),
KEY `idx_status` (`status`),
KEY `idx_created_at` (`created_at`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='订单表';
CREATE TABLE IF NOT EXISTS `order_item` (
`id` BIGINT UNSIGNED NOT NULL AUTO_INCREMENT COMMENT '订单项ID(主键)',
`order_id` BIGINT UNSIGNED NOT NULL COMMENT '订单ID(关联order表)',
`order_no` VARCHAR(32) NOT NULL COMMENT '订单编号(冗余,便于查询)',
`product_id` BIGINT UNSIGNED NOT NULL COMMENT '商品ID(关联product表)',
`product_name` VARCHAR(200) NOT NULL COMMENT '商品名称(冗余,避免商品删除后丢失)',
`product_image` VARCHAR(255) NOT NULL COMMENT '商品主图(冗余)',
`price` DECIMAL(10,2) NOT NULL COMMENT '购买单价(元)',
`quantity` INT NOT NULL COMMENT '购买数量',
`total_amount` DECIMAL(10,2) NOT NULL COMMENT '订单项总金额(元,单价×数量)',
`created_at` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
PRIMARY KEY (`id`),
KEY `idx_order_id` (`order_id`),
KEY `idx_product_id` (`product_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='订单项表';
CREATE TABLE IF NOT EXISTS `cart` (
`id` BIGINT UNSIGNED NOT NULL AUTO_INCREMENT COMMENT '购物车ID(主键)',
`user_id` BIGINT UNSIGNED NOT NULL COMMENT '用户ID(关联user表)',
`product_id` BIGINT UNSIGNED NOT NULL COMMENT '商品ID(关联product表)',
`quantity` INT NOT NULL DEFAULT 1 COMMENT '商品数量',
`checked` TINYINT NOT NULL DEFAULT 1 COMMENT '是否选中(0-否,1-是,结算用)',
`created_at` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
`updated_at` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间',
PRIMARY KEY (`id`),
UNIQUE KEY `uk_user_product` (`user_id`,`product_id`),
KEY `idx_user_id` (`user_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='购物车表';
模拟数据
sql
INSERT INTO `user` (`username`, `password`, `phone`, `email`, `gender`, `birth_date`) VALUES
('张三', '$2a$10$eU5x8P7eF9G0h1J2K3L4M5N6O7P8Q9R0S1T2U3V4W5X6Y7Z8', '13800138001', 'zhangsan@example.com', 1, '1990-01-15'),
('李四', '$2a$10$eU5x8P7eF9G0h1J2K3L4M5N6O7P8Q9R0S1T2U3V4W5X6Y7Z8', '13800138002', 'lisi@example.com', 2, '1995-05-20'),
('王五', '$2a$10$eU5x8P7eF9G0h1J2K3L4M5N6O7P8Q9R0S1T2U3V4W5X6Y7Z8', '13800138003', 'wangwu@example.com', 1, '1988-10-01'),
('用户20', '$2a$10$eU5x8P7eF9G0h1J2K3L4M5N6O7P8Q9R0S1T2U3V4W5X6Y7Z8', '13800138020', 'user20@example.com', 0, '2000-01-01');
INSERT INTO `category` (`name`, `parent_id`, `level`, `sort`) VALUES
('电子产品', 0, 1, 1),
('手机', 1, 2, 1),
('电脑', 1, 2, 2),
('家用电器', 0, 1, 2),
('冰箱', 4, 2, 1),
('洗衣机', 4, 2, 2),
('服装鞋帽', 0, 1, 3),
('男装', 7, 2, 1),
('女装', 7, 2, 2),
('童装', 7, 2, 3);
INSERT INTO `product` (`category_id`, `name`, `subtitle`, `main_image`, `price`, `market_price`, `stock`, `sales`, `description`) VALUES
(2, 'Apple iPhone 15 Pro', 'A17 Pro芯片,钛金属机身', 'https://example.com/iphone15pro.jpg', 7999.00, 8999.00, 100, 50, 'iPhone 15 Pro采用A17 Pro芯片,性能强劲,拍照出色'),
(2, '华为Mate 60 Pro', '麒麟9000S芯片,卫星通信', 'https://example.com/mate60pro.jpg', 6999.00, 7599.00, 80, 30, '华为Mate 60 Pro支持卫星通话,国产芯片标杆'),
(3, '联想拯救者Y9000P', 'i9-13900H,4060显卡', 'https://example.com/y9000p.jpg', 9999.00, 10999.00, 50, 20, '游戏本性能猛兽,办公游戏两不误'),
(3, 'MacBook Pro 14', 'M3 Pro芯片,16GB内存', 'https://example.com/macbookpro14.jpg', 13999.00, 14999.00, 30, 15, '苹果笔记本,续航强劲,适合设计师'),
(5, '海尔500升法式多门冰箱', '一级能效,风冷无霜', 'https://example.com/haier500.jpg', 4999.00, 5499.00, 20, 10, '大容量冰箱,节能静音'),
(10, '巴拉巴拉儿童连衣裙', '纯棉透气,公主风', 'https://example.com/balabala.jpg', 199.00, 299.00, 200, 80, '儿童连衣裙,舒适亲肤');
-- 为商品1(iPhone 15 Pro)添加3张图
INSERT INTO `product_image` (`product_id`, `image_url`, `sort`) VALUES
(1, 'https://example.com/iphone15pro_1.jpg', 0), -- 主图
(1, 'https://example.com/iphone15pro_2.jpg', 1), -- 详情图1
(1, 'https://example.com/iphone15pro_3.jpg', 2), -- 详情图2
(2, 'https://example.com/mate60pro_1.jpg', 0),
(2, 'https://example.com/mate60pro_2.jpg', 1),
(2, 'https://example.com/mate60pro_3.jpg', 2),
(30, 'https://example.com/product30_1.jpg', 0),
(30, 'https://example.com/product30_2.jpg', 1),
(30, 'https://example.com/product30_3.jpg', 2);
-- 用户1(id=1)的地址
INSERT INTO `shipping` (`user_id`, `receiver_name`, `receiver_phone`, `province`, `city`, `district`, `detail_address`, `is_default`) VALUES
(1, '张三', '13800138001', '北京市', '北京市', '朝阳区', '建国路88号SOHO现代城A座1001室', 1),
(1, '张三', '13800138001', '上海市', '上海市', '浦东新区', '张江高科技园区博云路2号', 0),
-- 用户2(id=2)的地址
(2, '李四', '13800138002', '广东省', '广州市', '天河区', '天河路385号天俊阁2302室', 1),
(2, '李四', '13800138002', '广东省', '深圳市', '南山区', '科技园南区科苑路1号', 0),
(20, '用户20', '13800138020', '浙江省', '杭州市', '西湖区', '文二路391号西湖国际科技大厦B座501室', 1),
(20, '用户20', '13800138020', '江苏省', '南京市', '鼓楼区', '中山北路2号紫峰大厦1008室', 0);
INSERT INTO `order` (`order_no`, `user_id`, `shipping_id`, `total_amount`, `pay_amount`, `freight_amount`, `discount_amount`, `pay_type`, `status`, `payment_time`, `ship_time`, `receive_time`) VALUES
-- 用户1的订单(order_no=2024052010000001)
('2024052010000001', 1, 1, 7999.00, 7999.00, 0.00, 0.00, 1, 3, '2024-05-20 10:05:30', '2024-05-20 15:30:00', '2024-05-22 09:10:20'),
-- 用户1的另一个订单(order_no=2024052514000002)
('2024052514000002', 1, 2, 4999.00, 4999.00, 0.00, 0.00, 2, 3, '2024-05-25 14:10:00', '2024-05-25 16:40:00', '2024-05-27 11:20:30'),
-- 用户2的订单(order_no=2024052209000003)
('2024052209000003', 2, 3, 6999.00, 6999.00, 0.00, 0.00, 1, 3, '2024-05-22 09:15:00', '2024-05-22 13:20:00', '2024-05-24 10:30:40'),
('2024060116000020', 20, 39, 199.00, 199.00, 0.00, 0.00, 2, 2, '2024-06-01 16:20:00', '2024-06-01 18:00:00', NULL); -- 待收货
-- 订单1(order_id=1,iPhone 15 Pro)
INSERT INTO `order_item` (`order_id`, `order_no`, `product_id`, `product_name`, `product_image`, `price`, `quantity`, `total_amount`) VALUES
(1, '2024052010000001', 1, 'Apple iPhone 15 Pro', 'https://example.com/iphone15pro.jpg', 7999.00, 1, 7999.00),
-- 订单2(order_id=2,海尔冰箱)
(2, '2024052514000002', 5, '海尔500升法式多门冰箱', 'https://example.com/haier500.jpg', 4999.00, 1, 4999.00),
-- 订单3(order_id=3,华为Mate 60 Pro + 联想拯救者Y9000P)
(3, '2024052209000003', 2, '华为Mate 60 Pro', 'https://example.com/mate60pro.jpg', 6999.00, 1, 6999.00),
(3, '2024052209000003', 3, '联想拯救者Y9000P', 'https://example.com/y9000p.jpg', 9999.00, 1, 9999.00),
(20, '2024060116000020', 30, '巴拉巴拉儿童连衣裙', 'https://example.com/balabala.jpg', 199.00, 1, 199.00);
-- 用户1的购物车
INSERT INTO `cart` (`user_id`, `product_id`, `quantity`, `checked`) VALUES
(1, 3, 1, 1), -- 联想拯救者Y9000P
(1, 4, 1, 1), -- MacBook Pro 14
(1, 6, 1, 0), -- 洗衣机(未选中)
-- 用户2的购物车
(2, 4, 1, 1), -- MacBook Pro 14
(2, 5, 1, 0), -- 海尔冰箱(未选中)
(2, 7, 1, 1), -- 男装T恤
(20, 28, 1, 1), -- 童装裤子
(20, 29, 1, 1), -- 童装外套
(20, 30, 1, 0); -- 儿童连衣裙(未选中)
数据库配置文件
sql
server:
port: 8080
spring:
application:
name: text-to-sql
profiles:
active: local
datasource:
driver-class-name: com.mysql.cj.jdbc.Driver
url: jdbc:mysql://127.0.0.1:3306/text_to_sql?useSSL=false&serverTimezone=Asia/Shanghai&allowPublicKeyRetrieval=true&nullCatalogMeansCurrent=true&rewriteBatchedStatements=true # MySQL Connector/J 8.X ?????
username: root
password: 123456
hikari:
maximum-pool-size: 10
minimum-idle: 2
idle-timeout: 300000
connection-timeout: 30000
编写代码
第一步获取库中所有表的建表DDL语句
代码如下(也是AI生成)
java
/**
* MySQL DDL语句生成工具类
*/
@Service
public class MysqlDdlGenerator {
@Autowired
private JdbcTemplate jdbcTemplate;
/**
* 获取指定数据库中所有表的DDL语句
*
* @param databaseName 数据库名称(schema名称)
* @return 所有表的DDL语句,每个表的DDL以";\n\n"分隔
* @throws RuntimeException 当数据库连接或查询失败时抛出
*/
public String getAllTableDdl(String databaseName) {
// 1. 校验数据库名称
if (databaseName == null || databaseName.trim().isEmpty()) {
throw new IllegalArgumentException("数据库名称不能为空");
}
// 2. 查询指定数据库下的所有表名(排除视图,只保留表)
List<String> tableNames = getTableNames(databaseName);
if (tableNames.isEmpty()) {
return "数据库【" + databaseName + "】中未找到任何表";
}
// 3. 循环获取每个表的DDL
StringBuilder allDdl = new StringBuilder();
for (String tableName : tableNames) {
String tableDdl = getSingleTableDdl(databaseName, tableName);
allDdl.append(tableDdl).append(";\n\n"); // 每个表的DDL以分号和空行分隔
}
return allDdl.toString();
}
/**
* 获取指定数据库中的所有表名(仅表,不包含视图)
*/
private List<String> getTableNames(String databaseName) {
String sql = "SELECT TABLE_NAME " +
"FROM information_schema.TABLES " +
"WHERE TABLE_SCHEMA = ? " + // 指定数据库
"AND TABLE_TYPE = 'BASE TABLE'"; // 只查询表(排除视图)
return jdbcTemplate.queryForList(sql, String.class, databaseName);
}
/**
* 获取单张表的DDL语句
*/
private String getSingleTableDdl(String databaseName, String tableName) {
try {
// 执行SHOW CREATE TABLE,MySQL会返回完整的建表语句
// 注意表名和数据库名需要用反引号包裹,避免关键字冲突
String sql = "SHOW CREATE TABLE `" + databaseName + "`.`" + tableName + "`";
Map<String, Object> resultMap = jdbcTemplate.queryForMap(sql);
// 结果中"Create Table"字段对应建表语句
return (String) resultMap.get("Create Table");
} catch (Exception e) {
throw new RuntimeException("获取表【" + tableName + "】的DDL失败:" + e.getMessage(), e);
}
}
}
编写测试类
java
@SpringBootTest
class MysqlDdlGeneratorTest {
@Resource
private MysqlDdlGenerator mysqlDdlGenerator;
@Test
void getAllTableDdl() {
String textToSql = mysqlDdlGenerator.getAllTableDdl("text_to_sql");
System.out.println(textToSql);
}
}
执行结果如下

成功拿到了所有表的建表DDL语句
第二部就是编写提示词
这里放到下一章实现