From 1e768a7409d273c14bfced0a7311e8e58f93f003 Mon Sep 17 00:00:00 2001 From: wanghanlin <1533525126@qq.com> Date: Fri, 28 Aug 2026 08:17:51 +0800 Subject: [PATCH] =?UTF-8?q?fix(service):=20=E4=BF=AE=E5=A4=8D=E8=A7=92?= =?UTF-8?q?=E8=89=B2=E5=88=9B=E5=BB=BA=E4=B8=BB=E9=94=AE=E8=8E=B7=E5=8F=96?= =?UTF-8?q?=E5=BC=82=E5=B8=B8?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 创建角色改用 RETURNING id 显式取回主键,避免 PostgreSQL JDBC 对 RETURN_GENERATED_KEYS 追加 RETURNING * 导致 GeneratedKeyHolder.getKey() 抛 multiple keys 异常 --- .../service/CustomerServiceRoleService.java | 25 ++++++------------- 1 file changed, 7 insertions(+), 18 deletions(-) diff --git a/src/main/java/com/wok/supportbot/service/CustomerServiceRoleService.java b/src/main/java/com/wok/supportbot/service/CustomerServiceRoleService.java index 4a57a58..8dcae65 100644 --- a/src/main/java/com/wok/supportbot/service/CustomerServiceRoleService.java +++ b/src/main/java/com/wok/supportbot/service/CustomerServiceRoleService.java @@ -5,13 +5,9 @@ import com.fasterxml.jackson.databind.ObjectMapper; import lombok.extern.slf4j.Slf4j; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.jdbc.core.JdbcTemplate; -import org.springframework.jdbc.support.GeneratedKeyHolder; -import org.springframework.jdbc.support.KeyHolder; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; -import java.sql.PreparedStatement; -import java.sql.Statement; import java.util.ArrayList; import java.util.LinkedHashMap; import java.util.List; @@ -114,23 +110,16 @@ public class CustomerServiceRoleService { String key = (roleKey == null || roleKey.trim().isEmpty()) ? "role_" + System.currentTimeMillis() : roleKey.trim(); - KeyHolder keyHolder = new GeneratedKeyHolder(); - jdbcTemplate.update(con -> { - PreparedStatement ps = con.prepareStatement( - "INSERT INTO customer_service_role (role_key, name, description, prompt, enabled) VALUES (?, ?, ?, ?, ?)", - Statement.RETURN_GENERATED_KEYS); - ps.setString(1, key); - ps.setString(2, name.trim()); - ps.setString(3, description); - ps.setString(4, prompt); - ps.setBoolean(5, enabled != null ? enabled : true); - return ps; - }, keyHolder); - Number generatedId = keyHolder.getKey(); + // 使用 RETURNING id 显式取回主键,避免 PostgreSQL JDBC 对 RETURN_GENERATED_KEYS + // 追加 RETURNING *(返回整行多列),导致 GeneratedKeyHolder.getKey() 抛"multiple keys"异常 + Long generatedId = jdbcTemplate.queryForObject( + "INSERT INTO customer_service_role (role_key, name, description, prompt, enabled) VALUES (?, ?, ?, ?, ?) RETURNING id", + Long.class, + key, name.trim(), description, prompt, enabled != null ? enabled : true); if (generatedId == null) { throw new RuntimeException("创建角色失败:无法获取自动生成的 ID"); } - return generatedId.longValue(); + return generatedId; } /**