Merge pull request #3279 from xinnan-tech/fix/issue-3276-context-provider

fix: 修复 ContextProviderListTypeHandler 多版本兼容问题
This commit is contained in:
CGD
2026-07-17 09:28:14 +08:00
committed by GitHub
21 changed files with 298 additions and 66 deletions
+50 -2
View File
@@ -21,6 +21,9 @@
<junit.version>5.10.1</junit.version>
<druid.version>1.2.20</druid.version>
<mybatisplus.version>3.5.5</mybatisplus.version>
<mybatisplus.starter.artifactId>mybatis-plus-boot-starter</mybatisplus.starter.artifactId>
<mybatis-spring.version>3.0.3</mybatis-spring.version>
<mybatisplus.compat.source>src/mybatis-plus-legacy/java</mybatisplus.compat.source>
<hutool.version>5.8.24</hutool.version>
<jsoup.version>1.19.1</jsoup.version>
<knife4j.version>4.6.0</knife4j.version>
@@ -176,13 +179,13 @@
</dependency>
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-boot-starter</artifactId>
<artifactId>${mybatisplus.starter.artifactId}</artifactId>
<version>${mybatisplus.version}</version>
</dependency>
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis-spring</artifactId>
<version>3.0.3</version>
<version>${mybatis-spring.version}</version>
</dependency>
<dependency>
<groupId>cn.hutool</groupId>
@@ -265,9 +268,54 @@
</snapshots>
</pluginRepository>
</pluginRepositories>
<profiles>
<!-- Use -Pmybatis-plus-3.5.6 or -Pmybatis-plus-3.5.17 with clean; adapters share class names. -->
<profile>
<id>mybatis-plus-3.5.6</id>
<properties>
<mybatisplus.version>3.5.6</mybatisplus.version>
</properties>
</profile>
<!-- MyBatis-Plus 3.5.17 moved Spring services and split out JSqlParser support. -->
<profile>
<id>mybatis-plus-3.5.17</id>
<properties>
<mybatisplus.version>3.5.17</mybatisplus.version>
<mybatisplus.starter.artifactId>mybatis-plus-spring-boot3-starter</mybatisplus.starter.artifactId>
<mybatis-spring.version>3.0.5</mybatis-spring.version>
<mybatisplus.compat.source>src/mybatis-plus-modern/java</mybatisplus.compat.source>
</properties>
<dependencies>
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-jsqlparser-4.9</artifactId>
<version>${mybatisplus.version}</version>
</dependency>
</dependencies>
</profile>
</profiles>
<build>
<finalName>${project.artifactId}</finalName>
<plugins>
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>build-helper-maven-plugin</artifactId>
<version>3.6.0</version>
<executions>
<execution>
<id>add-mybatis-plus-compatibility-sources</id>
<phase>generate-sources</phase>
<goals>
<goal>add-source</goal>
</goals>
<configuration>
<sources>
<source>${project.basedir}/${mybatisplus.compat.source}</source>
</sources>
</configuration>
</execution>
</executions>
</plugin>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
@@ -27,6 +27,7 @@ import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.toolkit.SqlHelper;
import xiaozhi.common.constant.Constant;
import xiaozhi.common.mybatisplus.MybatisPlusBatchHelper;
import xiaozhi.common.page.PageData;
import xiaozhi.common.service.BaseService;
import xiaozhi.common.utils.ConvertUtils;
@@ -181,8 +182,9 @@ public abstract class BaseServiceImpl<M extends BaseMapper<T>, T> implements Bas
* 执行批量操作
*/
@SuppressWarnings("deprecation")
protected <E> boolean executeBatch(Collection<E> list, int batchSize, BiConsumer<SqlSession, E> consumer) {
return SqlHelper.executeBatch(this.currentModelClass(), this.log, list, batchSize, consumer);
protected <E> boolean executeBatch(Collection<E> list, int batchSize, BiConsumer<SqlSession, E> operation) {
return MybatisPlusBatchHelper.executeBatch(SqlHelper.sqlSessionFactory(this.currentModelClass()), this.log,
list, batchSize, operation);
}
@Override
@@ -227,4 +229,4 @@ public abstract class BaseServiceImpl<M extends BaseMapper<T>, T> implements Bas
public boolean deleteBatchIds(Collection<? extends Serializable> idList) {
return SqlHelper.retBool(baseDao.deleteBatchIds(idList));
}
}
}
@@ -1,7 +1,6 @@
package xiaozhi.modules.agent.service;
import com.baomidou.mybatisplus.extension.service.IService;
import xiaozhi.common.mybatisplus.MpService;
import xiaozhi.modules.agent.entity.AgentChatAudioEntity;
/**
@@ -11,7 +10,7 @@ import xiaozhi.modules.agent.entity.AgentChatAudioEntity;
* @version 1.0, 2025/5/8
* @since 1.0.0
*/
public interface AgentChatAudioService extends IService<AgentChatAudioEntity> {
public interface AgentChatAudioService extends MpService<AgentChatAudioEntity> {
/**
* 保存音频数据
*
@@ -3,9 +3,8 @@ package xiaozhi.modules.agent.service;
import java.util.List;
import java.util.Map;
import com.baomidou.mybatisplus.extension.service.IService;
import xiaozhi.common.page.PageData;
import xiaozhi.common.page.PageData;
import xiaozhi.common.mybatisplus.MpService;
import xiaozhi.modules.agent.dto.AgentChatHistoryDTO;
import xiaozhi.modules.agent.dto.AgentChatSessionDTO;
import xiaozhi.modules.agent.entity.AgentChatHistoryEntity;
@@ -18,7 +17,7 @@ import xiaozhi.modules.agent.vo.AgentChatHistoryUserVO;
* @version 1.0, 2025/4/30
* @since 1.0.0
*/
public interface AgentChatHistoryService extends IService<AgentChatHistoryEntity> {
public interface AgentChatHistoryService extends MpService<AgentChatHistoryEntity> {
/**
* 根据智能体ID获取会话列表
@@ -2,15 +2,14 @@ package xiaozhi.modules.agent.service;
import java.util.List;
import com.baomidou.mybatisplus.extension.service.IService;
import xiaozhi.common.mybatisplus.MpService;
import xiaozhi.modules.agent.entity.AgentPluginMapping;
/**
* @description 针对表【ai_agent_plugin_mapping(Agent与插件的唯一映射表)】的数据库操作Service
* @createDate 2025-05-25 22:33:17
*/
public interface AgentPluginMappingService extends IService<AgentPluginMapping> {
public interface AgentPluginMappingService extends MpService<AgentPluginMapping> {
/**
* 根据智能体id获取插件参数
@@ -1,7 +1,6 @@
package xiaozhi.modules.agent.service;
import com.baomidou.mybatisplus.extension.service.IService;
import xiaozhi.common.mybatisplus.MpService;
import xiaozhi.modules.agent.entity.AgentTemplateEntity;
/**
@@ -9,7 +8,7 @@ import xiaozhi.modules.agent.entity.AgentTemplateEntity;
* @description 针对表【ai_agent_template(智能体配置模板表)】的数据库操作Service
* @createDate 2025-03-22 11:48:18
*/
public interface AgentTemplateService extends IService<AgentTemplateEntity> {
public interface AgentTemplateService extends MpService<AgentTemplateEntity> {
/**
* 获取默认模板
@@ -2,8 +2,7 @@ package xiaozhi.modules.agent.service.impl;
import org.springframework.stereotype.Service;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import xiaozhi.common.mybatisplus.MpServiceImpl;
import xiaozhi.modules.agent.dao.AiAgentChatAudioDao;
import xiaozhi.modules.agent.entity.AgentChatAudioEntity;
import xiaozhi.modules.agent.service.AgentChatAudioService;
@@ -16,7 +15,7 @@ import xiaozhi.modules.agent.service.AgentChatAudioService;
* @since 1.0.0
*/
@Service
public class AgentChatAudioServiceImpl extends ServiceImpl<AiAgentChatAudioDao, AgentChatAudioEntity>
public class AgentChatAudioServiceImpl extends MpServiceImpl<AiAgentChatAudioDao, AgentChatAudioEntity>
implements AgentChatAudioService {
@Override
public String saveAudio(byte[] audioData) {
@@ -14,9 +14,8 @@ import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import xiaozhi.common.constant.Constant;
import xiaozhi.common.mybatisplus.MpServiceImpl;
import xiaozhi.common.page.PageData;
import xiaozhi.common.utils.ConvertUtils;
import xiaozhi.common.utils.JsonUtils;
@@ -39,7 +38,7 @@ import xiaozhi.modules.agent.vo.AgentChatHistoryUserVO;
*/
@Service
@RequiredArgsConstructor
public class AgentChatHistoryServiceImpl extends ServiceImpl<AiAgentChatHistoryDao, AgentChatHistoryEntity>
public class AgentChatHistoryServiceImpl extends MpServiceImpl<AiAgentChatHistoryDao, AgentChatHistoryEntity>
implements AgentChatHistoryService {
private final AgentChatTitleService agentChatTitleService;
@@ -9,11 +9,10 @@ import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import xiaozhi.common.utils.JsonUtils;
import xiaozhi.common.mybatisplus.MpServiceImpl;
import xiaozhi.modules.agent.dao.AgentPluginMappingMapper;
import xiaozhi.modules.agent.entity.AgentPluginMapping;
import xiaozhi.modules.agent.service.AgentPluginMappingService;
@@ -29,7 +28,7 @@ import xiaozhi.modules.model.service.ModelConfigService;
@Service
@RequiredArgsConstructor
@Slf4j
public class AgentPluginMappingServiceImpl extends ServiceImpl<AgentPluginMappingMapper, AgentPluginMapping>
public class AgentPluginMappingServiceImpl extends MpServiceImpl<AgentPluginMappingMapper, AgentPluginMapping>
implements AgentPluginMappingService {
private final AgentPluginMappingMapper agentPluginMappingMapper;
private final KnowledgeBaseService knowledgeBaseService;
@@ -4,8 +4,7 @@ import org.springframework.stereotype.Service;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import xiaozhi.common.mybatisplus.MpServiceImpl;
import xiaozhi.modules.agent.dao.AgentTemplateDao;
import xiaozhi.modules.agent.entity.AgentTemplateEntity;
import xiaozhi.modules.agent.service.AgentTemplateService;
@@ -21,7 +20,7 @@ import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
* @createDate 2025-03-22 11:48:18
*/
@Service
public class AgentTemplateServiceImpl extends ServiceImpl<AgentTemplateDao, AgentTemplateEntity>
public class AgentTemplateServiceImpl extends MpServiceImpl<AgentTemplateDao, AgentTemplateEntity>
implements AgentTemplateService {
/**
@@ -22,12 +22,11 @@ import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import xiaozhi.common.constant.Constant;
import xiaozhi.common.exception.ErrorCode;
import xiaozhi.common.exception.RenException;
import xiaozhi.common.mybatisplus.MpServiceImpl;
import xiaozhi.common.utils.ConvertUtils;
import xiaozhi.common.utils.JsonUtils;
import xiaozhi.modules.agent.dao.AgentVoicePrintDao;
@@ -46,7 +45,7 @@ import xiaozhi.modules.sys.service.SysParamsService;
*/
@Service
@Slf4j
public class AgentVoicePrintServiceImpl extends ServiceImpl<AgentVoicePrintDao, AgentVoicePrintEntity>
public class AgentVoicePrintServiceImpl extends MpServiceImpl<AgentVoicePrintDao, AgentVoicePrintEntity>
implements AgentVoicePrintService {
private final AgentChatAudioService agentChatAudioService;
private final RestTemplate restTemplate;
@@ -1,31 +1,59 @@
package xiaozhi.modules.agent.typehandler;
import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Collections;
import java.util.List;
import org.apache.commons.lang3.StringUtils;
import org.apache.ibatis.type.BaseTypeHandler;
import org.apache.ibatis.type.JdbcType;
import com.baomidou.mybatisplus.extension.handlers.AbstractJsonTypeHandler;
import com.fasterxml.jackson.core.type.TypeReference;
import xiaozhi.common.utils.JsonUtils;
import xiaozhi.modules.agent.dto.ContextProviderDTO;
public class ContextProviderListTypeHandler extends AbstractJsonTypeHandler<List<ContextProviderDTO>> {
/**
* JSON type handler for context providers.
*
* <p>Do not extend MyBatis-Plus {@code AbstractJsonTypeHandler}: its constructor and JSON handler
* contract changed in MyBatis-Plus 3.5.6. {@link BaseTypeHandler} is part of MyBatis itself and
* keeps this handler compatible with both 3.5.5 and newer MyBatis-Plus releases.</p>
*/
public class ContextProviderListTypeHandler extends BaseTypeHandler<List<ContextProviderDTO>> {
private static final TypeReference<List<ContextProviderDTO>> CONTEXT_PROVIDER_LIST_TYPE = new TypeReference<>() {
};
@Override
protected List<ContextProviderDTO> parse(String json) {
public void setNonNullParameter(PreparedStatement ps, int i, List<ContextProviderDTO> parameter,
JdbcType jdbcType) throws SQLException {
ps.setString(i, JsonUtils.toJsonString(parameter));
}
@Override
public List<ContextProviderDTO> getNullableResult(ResultSet rs, String columnName) throws SQLException {
return parseNullable(rs.getString(columnName));
}
@Override
public List<ContextProviderDTO> getNullableResult(ResultSet rs, int columnIndex) throws SQLException {
return parseNullable(rs.getString(columnIndex));
}
@Override
public List<ContextProviderDTO> getNullableResult(CallableStatement cs, int columnIndex) throws SQLException {
return parseNullable(cs.getString(columnIndex));
}
private List<ContextProviderDTO> parseNullable(String json) {
if (StringUtils.isBlank(json)) {
return Collections.emptyList();
return null;
}
List<ContextProviderDTO> providers = JsonUtils.parseObject(json, CONTEXT_PROVIDER_LIST_TYPE);
return providers == null ? Collections.emptyList() : providers;
}
@Override
protected String toJson(List<ContextProviderDTO> obj) {
return JsonUtils.toJsonString(obj == null ? Collections.emptyList() : obj);
}
}
@@ -0,0 +1,7 @@
package xiaozhi.common.mybatisplus;
/**
* Stable project-level alias for the MyBatis-Plus service contract used by 3.5.5 and 3.5.6.
*/
public interface MpService<T> extends com.baomidou.mybatisplus.extension.service.IService<T> {
}
@@ -0,0 +1,10 @@
package xiaozhi.common.mybatisplus;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
/**
* Stable project-level base class for the MyBatis-Plus 3.5.5/3.5.6 service implementation.
*/
public class MpServiceImpl<M extends BaseMapper<T>, T>
extends com.baomidou.mybatisplus.extension.service.impl.ServiceImpl<M, T> implements MpService<T> {
}
@@ -0,0 +1,24 @@
package xiaozhi.common.mybatisplus;
import java.util.Collection;
import java.util.function.BiConsumer;
import org.apache.ibatis.logging.Log;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import com.baomidou.mybatisplus.extension.toolkit.SqlHelper;
/**
* Type-safe access to the MyBatis-Plus 3.5.5/3.5.6 batch callback API.
*/
public final class MybatisPlusBatchHelper {
private MybatisPlusBatchHelper() {
}
@SuppressWarnings("deprecation")
public static <E> boolean executeBatch(SqlSessionFactory sqlSessionFactory, Log log, Collection<E> entities,
int batchSize, BiConsumer<SqlSession, E> operation) {
return SqlHelper.executeBatch(sqlSessionFactory, log, entities, batchSize, operation);
}
}
@@ -0,0 +1,7 @@
package xiaozhi.common.mybatisplus;
/**
* Stable project-level alias for the MyBatis-Plus 3.5.17 Spring service contract.
*/
public interface MpService<T> extends com.baomidou.mybatisplus.spring.service.IService<T> {
}
@@ -0,0 +1,10 @@
package xiaozhi.common.mybatisplus;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
/**
* Stable project-level base class for the MyBatis-Plus 3.5.17 Spring service implementation.
*/
public class MpServiceImpl<M extends BaseMapper<T>, T>
extends com.baomidou.mybatisplus.spring.service.impl.ServiceImpl<M, T> implements MpService<T> {
}
@@ -0,0 +1,27 @@
package xiaozhi.common.mybatisplus;
import java.util.Collection;
import java.util.function.BiConsumer;
import org.apache.ibatis.logging.Log;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import com.baomidou.mybatisplus.extension.toolkit.SqlHelper;
/**
* Type-safe access to the MyBatis-Plus 3.5.17 batch callback API.
*/
public final class MybatisPlusBatchHelper {
private MybatisPlusBatchHelper() {
}
@SuppressWarnings("deprecation")
public static <E> boolean executeBatch(SqlSessionFactory sqlSessionFactory, Log log, Collection<E> entities,
int batchSize, BiConsumer<SqlSession, E> operation) {
return SqlHelper.executeBatch(sqlSessionFactory, log, entities, batchSize, (sqlSession, entity) -> {
operation.accept(sqlSession, entity);
return 0;
});
}
}
@@ -0,0 +1,47 @@
package xiaozhi.common.mybatisplus;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertSame;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import java.util.ArrayList;
import java.util.List;
import org.apache.ibatis.executor.BatchResult;
import org.apache.ibatis.logging.Log;
import org.apache.ibatis.mapping.MappedStatement;
import org.apache.ibatis.session.ExecutorType;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.junit.jupiter.api.Test;
class MybatisPlusBatchHelperTest {
@Test
void executesBatchThroughSelectedVersionAdapter() {
SqlSessionFactory sqlSessionFactory = mock(SqlSessionFactory.class);
SqlSession sqlSession = mock(SqlSession.class);
Log log = mock(Log.class);
when(sqlSessionFactory.openSession(ExecutorType.BATCH)).thenReturn(sqlSession);
BatchResult batchResult = new BatchResult(mock(MappedStatement.class), "INSERT");
batchResult.setUpdateCounts(new int[] { 1, 1 });
when(sqlSession.flushStatements()).thenReturn(List.of(batchResult));
List<String> processed = new ArrayList<>();
boolean result = MybatisPlusBatchHelper.executeBatch(sqlSessionFactory, log, List.of("first", "second"), 2,
(session, entity) -> {
assertSame(sqlSession, session);
processed.add(entity);
});
assertTrue(result);
assertEquals(List.of("first", "second"), processed);
verify(sqlSession).flushStatements();
verify(sqlSession).commit(true);
verify(sqlSession).close();
}
}
@@ -1096,13 +1096,13 @@ class AgentSnapshotServiceImplTest {
when(snapshotService.getCurrentVersionNo(agentId)).thenReturn(0);
when(contextProviderService.getByAgentId(agentId)).thenReturn(null);
when(correctWordFileService.getAgentCorrectWordFileIds(agentId)).thenReturn(List.of());
when(agentDao.updateById(any())).thenReturn(1);
when(agentDao.updateById(any(AgentEntity.class))).thenReturn(1);
service.updateAgentById(agentId, update);
InOrder inOrder = inOrder(agentDao, snapshotService);
inOrder.verify(snapshotService).createSnapshot(agentId, "initial");
inOrder.verify(agentDao).updateById(argThat(agent -> "new-name".equals(agent.getAgentName())));
inOrder.verify(agentDao).updateById(argThat((AgentEntity agent) -> "new-name".equals(agent.getAgentName())));
inOrder.verify(snapshotService).createSnapshot(agentId, "config");
}
@@ -1130,13 +1130,13 @@ class AgentSnapshotServiceImplTest {
when(snapshotService.getCurrentVersionNo(agentId)).thenReturn(4);
when(contextProviderService.getByAgentId(agentId)).thenReturn(null);
when(correctWordFileService.getAgentCorrectWordFileIds(agentId)).thenReturn(List.of());
when(agentDao.updateById(any())).thenReturn(1);
when(agentDao.updateById(any(AgentEntity.class))).thenReturn(1);
service.updateAgentById(agentId, update);
InOrder inOrder = inOrder(agentDao, snapshotService);
inOrder.verify(snapshotService).createSnapshot(agentId, "current");
inOrder.verify(agentDao).updateById(argThat(agent -> "new-name".equals(agent.getAgentName())));
inOrder.verify(agentDao).updateById(argThat((AgentEntity agent) -> "new-name".equals(agent.getAgentName())));
inOrder.verify(snapshotService).createSnapshot(agentId, "config");
}
@@ -1160,7 +1160,7 @@ class AgentSnapshotServiceImplTest {
when(templateService.getDefaultTemplate()).thenReturn(template);
when(timbreService.getDefaultLanguageById("TTS_EdgeTTS0001")).thenReturn("普通话");
when(agentDao.insert(any())).thenReturn(1);
when(agentDao.insert(any(AgentEntity.class))).thenReturn(1);
AgentCreateDTO dto = new AgentCreateDTO();
dto.setAgentName("test123");
@@ -1168,7 +1168,7 @@ class AgentSnapshotServiceImplTest {
String agentId = service.createAgent(dto);
InOrder inOrder = inOrder(agentDao, pluginMappingService, snapshotService);
inOrder.verify(agentDao).insert(argThat(agent -> "test123".equals(agent.getAgentName())
inOrder.verify(agentDao).insert(argThat((AgentEntity agent) -> "test123".equals(agent.getAgentName())
&& "普通话".equals(agent.getTtsLanguage())
&& "".equals(agent.getSummaryMemory())
&& Integer.valueOf(0).equals(agent.getChatHistoryConf())));
@@ -1834,8 +1834,8 @@ class AgentSnapshotServiceImplTest {
assertTrue(error.getCause() instanceof RenException);
assertEquals("快照引用的标签已被删除,无法恢复,请先重新创建或选择标签", error.getCause().getMessage());
verify(tagDao, never()).updateById(any());
verify(tagDao, never()).insert(any());
verify(tagDao, never()).updateById(any(AgentTagEntity.class));
verify(tagDao, never()).insert(any(AgentTagEntity.class));
}
private AgentInfoVO snapshotAgentInfo(String agentId, Long userId, String agentName, String summaryMemory) {
@@ -2,36 +2,30 @@ package xiaozhi.modules.agent.typehandler;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertInstanceOf;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.List;
import org.apache.ibatis.type.TypeHandler;
import org.apache.ibatis.type.TypeHandlerRegistry;
import org.junit.jupiter.api.Test;
import org.mockito.ArgumentCaptor;
import com.fasterxml.jackson.core.type.TypeReference;
import xiaozhi.common.utils.JsonUtils;
import xiaozhi.modules.agent.dto.ContextProviderDTO;
class ContextProviderListTypeHandlerTest {
private final ContextProviderListTypeHandler handler = new ContextProviderListTypeHandler();
@Test
void parseKeepsContextProviderDtoElementType() {
List<ContextProviderDTO> providers = handler
.parse("[{\"url\":\"https://example.com/context\",\"headers\":{\"Authorization\":\"Bearer token\"}}]");
assertEquals(1, providers.size());
assertInstanceOf(ContextProviderDTO.class, providers.get(0));
assertEquals("https://example.com/context", providers.get(0).getUrl());
assertEquals("Bearer token", providers.get(0).getHeaders().get("Authorization"));
}
@Test
void parseBlankJsonAsEmptyList() {
assertTrue(handler.parse(" ").isEmpty());
}
@Test
void myBatisCanInstantiateHandlerForListField() {
TypeHandler<?> typeHandler = new TypeHandlerRegistry().getInstance(List.class,
@@ -39,4 +33,41 @@ class ContextProviderListTypeHandlerTest {
assertInstanceOf(ContextProviderListTypeHandler.class, typeHandler);
}
@Test
void resultSetDeserializationKeepsContextProviderDtoElementType() throws Exception {
ResultSet resultSet = mock(ResultSet.class);
when(resultSet.getString("context_providers"))
.thenReturn("[{\"url\":\"https://example.com/context\",\"headers\":{\"Authorization\":\"Bearer token\"}}]");
List<ContextProviderDTO> providers = handler.getNullableResult(resultSet, "context_providers");
assertEquals(1, providers.size());
assertInstanceOf(ContextProviderDTO.class, providers.get(0));
assertEquals("https://example.com/context", providers.get(0).getUrl());
assertEquals("Bearer token", providers.get(0).getHeaders().get("Authorization"));
}
@Test
void sqlNullRemainsNull() throws Exception {
ResultSet resultSet = mock(ResultSet.class);
assertNull(handler.getNullableResult(resultSet, 1));
}
@Test
void serializesProviderListAsJson() throws Exception {
ContextProviderDTO provider = new ContextProviderDTO();
provider.setUrl("https://example.com/context");
PreparedStatement statement = mock(PreparedStatement.class);
handler.setNonNullParameter(statement, 1, List.of(provider), null);
ArgumentCaptor<String> json = ArgumentCaptor.forClass(String.class);
verify(statement).setString(eq(1), json.capture());
List<ContextProviderDTO> serialized = JsonUtils.parseObject(json.getValue(), new TypeReference<>() {
});
assertEquals(1, serialized.size());
assertEquals("https://example.com/context", serialized.get(0).getUrl());
}
}