最近刚接触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刚接触还不太会用,感觉坑还有点多..