Fix duplicate key error in agent plugin mapping creation

Prevent duplicate plugin mappings when creating new agents by checking
for existing mappings before inserting defaults. This resolves the
'Duplicate entry for key ai_agent_plugin_mapping.uk_agent_provider' error.

🤖 Generated with [Claude Code](https://claude.ai/code)

Co-Authored-By: Claude <noreply@anthropic.com>
This commit is contained in:
rahulpscraftech360 2025-09-06 13:38:01 +05:30
parent 0e791e9155
commit 43f111af9a

View file

@ -5,6 +5,7 @@ import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.UUID;
import java.util.function.Function;
import java.util.stream.Collectors;
@ -96,7 +97,7 @@ public class AgentServiceImpl extends BaseServiceImpl<AgentDao, AgentEntity> imp
// 如果智能体编码为空,自动生成一个带前缀的编码
if (entity.getAgentCode() == null || entity.getAgentCode().trim().isEmpty()) {
entity.setAgentCode("AGT_" + System.currentTimeMillis());
entity.setAgentCode("AGT_" + UUID.randomUUID().toString().replace("-", "").substring(0, 8));
}
// 如果排序字段为空,设置默认值0
@ -388,12 +389,27 @@ public class AgentServiceImpl extends BaseServiceImpl<AgentDao, AgentEntity> imp
// 保存智能体
insert(entity);
// 先检查是否已存在插件映射
List<AgentPluginMapping> existingMappings = agentPluginMappingService.list(
new QueryWrapper<AgentPluginMapping>()
.eq("agent_id", entity.getId()));
// 收集已存在的插件ID
Set<String> existingPluginIds = existingMappings.stream()
.map(AgentPluginMapping::getPluginId)
.collect(Collectors.toSet());
// 设置默认插件
List<AgentPluginMapping> toInsert = new ArrayList<>();
// 播放音乐、播放故事、查天气、查新闻
String[] pluginIds = new String[] { "SYSTEM_PLUGIN_MUSIC", "SYSTEM_PLUGIN_STORY",
"SYSTEM_PLUGIN_WEATHER", "SYSTEM_PLUGIN_NEWS_NEWSNOW" };
for (String pluginId : pluginIds) {
// 跳过已存在的插件映射
if (existingPluginIds.contains(pluginId)) {
continue;
}
ModelProviderDTO provider = modelProviderService.getById(pluginId);
if (provider == null) {
continue;
@ -412,8 +428,10 @@ public class AgentServiceImpl extends BaseServiceImpl<AgentDao, AgentEntity> imp
mapping.setAgentId(entity.getId());
toInsert.add(mapping);
}
// 保存默认插件
agentPluginMappingService.saveBatch(toInsert);
// 只有当有新插件需要插入时才保存
if (!toInsert.isEmpty()) {
agentPluginMappingService.saveBatch(toInsert);
}
return entity.getId();
}
}