tkmybties批量插入insertList报错主键不能为空解决办法

博客讲述了在使用MyBatis框架时遇到批量插入数据主键ID为空的错误,通过分析发现是因为实体类的ID未被正确处理。解决方案包括修改Mapper接口和XML配置,以支持String类型的主键ID,并提供了两种插入方法:动态SQL插入和单个插入。同时,博主提到了使用tk-mybatis的注意事项和相关依赖配置。
摘要由CSDN通过智能技术生成

最近刚接触tkmybties,今天调试接口突然发现批量插入报错,控制台日志显示主键id为空,这就很奇怪了,主键id是String类型并且赋值的UUID,直接上报错图,9个字段愣是给我整成了8个,并且主键id没了,ps:使用mysql数据库..

上mapper代码:

public interface HerosEntityMapper extends MyMapper<HerosEntity>{

}

public interface MyMapper<T> extends Mapper<T>, MySqlMapper<T> {

}

RegisterMapper
public interface MySqlMapper<T> extends InsertListMapper<T>, InsertUseGeneratedKeysMapper<T> {

}

@RegisterMapper
public interface InsertListMapper<T> {
    @Options(
        useGeneratedKeys = true
    )
    @InsertProvider(
        type = SpecialProvider.class,
        method = "dynamicSQL"
    )
    int insertList(List<? extends T> var1);
}

查询资料发现insertList使用条件:实体必须包含"id"属性并且必须是自增列

要想批量新增主键是String的处理办法:

public interface HerosEntityMapper extends MyMapper<HerosEntity>{
    int insertList(@Param("list") List<? extends HerosEntity> list);
}


<insert id="insertList">
    INSERT INTO t_heroes(
        id, a, b, c, d, e
    )VALUES
    <foreach collection="list" item="ele" index="index" separator=",">
        (
        #{ele.id,jdbcType=CHAR},
        #{ele.a,jdbcType=CHAR},
        #{ele.b,jdbcType=VARCHAR},
        #{ele.c,jdbcType=DECIMAL},
        #{ele.d,jdbcType=VARCHAR},
        #{ele.e,jdbcType=TIMESTAMP}
        )
    </foreach>
</insert>

也可以单个插入

herosEntityMapper.insertSelective(herosEntity);
最后说个重点,使用tkmybties在启动类上的注解
import tk.mybatis.spring.annotation.MapperScan;
@MapperScan("com.xxxx.xxxx.mapper")

mybatis注解,注意看两者的区别

import org.mybatis.spring.annotation.MapperScan;
@MapperScan("com.xxxx.xxxx.mapper")
pom中的变化,多了两个tk.mybatis的引用
<dependency>
	<groupId>org.mybatis.spring.boot</groupId>
	<artifactId>mybatis-spring-boot-starter</artifactId>
	<version>2.1.1</version>
</dependency>
<dependency>
	<groupId>tk.mybatis</groupId>
	<artifactId>mapper-spring-boot-starter</artifactId>
	<version>2.1.5</version>
</dependency>
<dependency>
	<groupId>tk.mybatis</groupId>
	<artifactId>mapper</artifactId>
	<version>4.0.4</version>
</dependency>

tkmybties刚接触还不太会用,感觉坑还有点多..

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值