package org.cloud.sonic.controller.typeHandler;
import com.google.common.base.Joiner;
import com.google.common.base.Splitter;
import org.apache.ibatis.type.JdbcType;
import org.apache.ibatis.type.MappedJdbcTypes;
import org.apache.ibatis.type.MappedTypes;
import org.apache.ibatis.type.TypeHandler;
import org.springframework.util.StringUtils;
import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
@MappedJdbcTypes(value = {JdbcType.VARCHAR}, includeNullJdbcType = true)
@MappedTypes({List.class})
public class ListIntegerTypeHandler implements TypeHandler<List<Integer>> {
@Override
public void setParameter(PreparedStatement preparedStatement, int i, List<Integer> list, JdbcType jdbcType) throws SQLException {
if (list == null || list.isEmpty()) {
preparedStatement.setString(i, ""); // 可以选择设置为空字符串或null
} else {
String parameter = Joiner.on(",").skipNulls().join(list);
System.out.println("Fetched value from DB1: " + parameter); // 输出数据库中的值
preparedStatement.setString(i, parameter);
}
}
@Override
public List<Integer> getResult(ResultSet resultSet, String columnName) throws SQLException {
String parameter = resultSet.getString(columnName);
System.out.println("Getting result from column name: " + columnName + ", value: " + parameter); // 输出获取的结果
return toIntegerList(parameter);
}
@Override
public List<Integer> getResult(ResultSet resultSet, int columnIndex) throws SQLException {
String parameter = resultSet.getString(columnIndex);
System.out.println("Getting result from column index: " + columnIndex + ", value: " + parameter); // 输出获取的结果
return toIntegerList(parameter);
}
@Override
public List<Integer> getResult(CallableStatement callableStatement, int columnIndex) throws SQLException {
String parameter = callableStatement.getString(columnIndex);
System.out.println("Getting result from callable statement: " + columnIndex + ", value: " + parameter); // 输出获取的结果
return toIntegerList(parameter);
}
private List<Integer> toIntegerList(String parameter) {
List<Integer> result = new ArrayList<>();
if (StringUtils.isEmpty(parameter)) {
return result; // 返回空列表
}
// 拆分字符串
List<String> splits = Splitter.on(",").trimResults().omitEmptyStrings().splitToList(parameter);
// 处理每个拆分出来的字符串,转换为 Integer
for (String split : splits) {
try {
result.add(Integer.valueOf(split));
} catch (NumberFormatException e) {
// 处理数字格式错误,可以记录日志或跳过
// 这里我们跳过非法格式的字符串
System.err.println("Invalid integer value in string: " + split);
}
}
return result;
}
}
mybatis-plus:
configuration:
type-handlers-package: org.cloud.sonic.controller.typeHandler
package org.cloud.sonic.controller.models.domain;
import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableField;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableName;
import com.fasterxml.jackson.annotation.JsonFormat;
import com.gitee.sunchenbin.mybatis.actable.annotation.Column;
import com.gitee.sunchenbin.mybatis.actable.annotation.Index;
import com.gitee.sunchenbin.mybatis.actable.annotation.IsAutoIncrement;
import com.gitee.sunchenbin.mybatis.actable.annotation.TableCharset;
import com.gitee.sunchenbin.mybatis.actable.annotation.TableComment;
import com.gitee.sunchenbin.mybatis.actable.annotation.TableEngine;
import com.gitee.sunchenbin.mybatis.actable.constants.MySqlCharsetConstant;
import com.gitee.sunchenbin.mybatis.actable.constants.MySqlEngineConstant;
import com.gitee.sunchenbin.mybatis.actable.constants.MySqlTypeConstant;
import io.swagger.v3.oas.annotations.media.Schema;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.experimental.Accessors;
import org.apache.commons.lang3.ObjectUtils;
import org.cloud.sonic.common.utils.UserUtils;
import org.cloud.sonic.controller.models.base.TypeConverter;
import org.cloud.sonic.controller.models.dto.TasksDTO;
import org.cloud.sonic.controller.typeHandler.ListIntegerTypeHandler;
import java.io.Serializable;
import java.util.Date;
import java.util.List;
@Schema(name = "Tasks对象", description = "")
@Data
//使生成的 setter 方法返回当前对象实例
@Accessors(chain = true)
//自动生成一个 builder 模式的构造方法
@Builder
//自动生成无参构造函数和全参构造函数
@NoArgsConstructor
@AllArgsConstructor
//指定实体类对应的数据库表名
@TableName(value = "tasks")
//添加表的注释
@TableComment("任务表")
//指定表的字符集和存储引擎
@TableCharset(MySqlCharsetConstant.DEFAULT)
@TableEngine(MySqlEngineConstant.InnoDB)
public class Tasks implements Serializable, TypeConverter<Tasks, TasksDTO> {
//标记主键字段,并指定主键生成策略
@TableId(value = "id", type = IdType.AUTO)
@IsAutoIncrement
private Integer id;
@TableField
@Column(value = "project_id", isNull = false, comment = "所属项目id")
@Index(value = "IDX_PROJECT_ID", columns = {"project_id"})
private Integer projectId;
@TableField("name")
@Column(isNull = false, comment = "name")
private String name;
@TableField("status")
@Column(isNull = false, comment = "状态")
private String status;
@Column(comment = "任务执行设备信息(设备表主键集合Id)")
@TableField(typeHandler = ListIntegerTypeHandler.class)
private List<Integer> deviceIds;
@Column(comment = "脚本文件")
@TableField(typeHandler = ListIntegerTypeHandler.class)
private List<Integer> scriptIds;
@Column(comment = "开始时间")
private Date startTime;
@Column(comment = "结束时间")
private Date endTime;
@TableField("case_num")
@Column(comment = "用例数量")
private Integer caseNum;
@TableField("package_url")
@Column(comment = "安装包链接")
private String packageUrl;
@TableField
@Column(value = "executor", comment = "执行人")
@Schema(description = "执行人")
private String executor;
@TableField
@Schema(description = "创建时间", required = true, example = "2021-08-15 11:10:00")
@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+8")
@Column(value = "create_time", type = MySqlTypeConstant.DATETIME, isNull = false, comment = "创建时间")
private Date createTime;
@TableField
@Schema(description = "更新时间", example = "2021-08-15 11:10:00")
@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+8")
@Column(value = "update_time", type = MySqlTypeConstant.DATETIME, comment = "更新时间")
private Date updateTime;
@TableField
@Column(value = "operator", isNull = false, comment = "操作人\"")
@Schema(description = "操作人", required = true)
private String operator;
public Tasks(TasksDTO tasksDTO, Date createTime) {
this.projectId = tasksDTO.getProjectId();
this.name = tasksDTO.getName();
this.status = tasksDTO.getStatus();
this.scriptIds = tasksDTO.getTestScriptIds();
this.deviceIds = tasksDTO.getDeviceIds();
this.packageUrl = tasksDTO.getPackageUrl();
this.operator = UserUtils.getCurrentUser();
if (!ObjectUtils.isEmpty(createTime)) {
this.createTime = createTime;
}
}
}
什么都配置好了 一直不能获取数据 百度基本上也是说要配置MyBatisPlusConfig
但是我配置就报错
package org.cloud.sonic.controller.config;
import com.baomidou.mybatisplus.extension.plugins.MybatisPlusInterceptor;
import com.baomidou.mybatisplus.extension.plugins.inner.PaginationInnerInterceptor;
import com.baomidou.mybatisplus.core.MybatisConfiguration;
import com.baomidou.mybatisplus.core.MybatisSqlSessionFactoryBean;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.type.TypeHandlerRegistry;
import org.cloud.sonic.controller.typeHandler.ListIntegerTypeHandler;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import javax.sql.DataSource;
@Configuration
@MapperScan("org.cloud.sonic.controller.mapper")
public class MyBatisPlusConfig {
@Bean
public MybatisPlusInterceptor mybatisPlusInterceptor() {
MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();
interceptor.addInnerInterceptor(new PaginationInnerInterceptor());
return interceptor;
}
@Bean
public SqlSessionFactory sqlSessionFactory(DataSource dataSource) throws Exception {
MybatisSqlSessionFactoryBean sessionFactory = new MybatisSqlSessionFactoryBean();
sessionFactory.setDataSource(dataSource);
// 手动注册类型处理器
MybatisConfiguration configuration = new MybatisConfiguration();
TypeHandlerRegistry typeHandlerRegistry = new TypeHandlerRegistry(configuration);
typeHandlerRegistry.register(List.class, String.class, new ListIntegerTypeHandler());
sessionFactory.setConfiguration(configuration);
// 如果有 mapper 文件,需要指定路径
sessionFactory.setMapperLocations(new PathMatchingResourcePatternResolver().getResources("classpath*:mapper/*.xml"));
return sessionFactory.getObject();
}
}
看了这篇文章Mybatis Plus typeHandler 指定自定义类型处理器 List转varchar_mybatisplus basetypehandler-优快云博客原来是缺少了
//指定实体类对应的数据库表名
@TableName(value = "tasks", autoResultMap = true)