目前在做mybatis数据迁移的时候遇到了不少坑,以前项目没有配置项,导致会产生不少bug,目前记录排坑了三种场景和其解决方案
驼峰转下划线之前项目中没引入,解决办法有三个:
- 蠢一点的方法就是手工在SQL里转
- 或者在外面使用工具类转
- mybatis的话可以配置驼峰问题
1.手工转,字段多的话很麻烦
select id as id ,store_id as storeId from xxx
2.外面写方法转
private LinkedHashMap humpToUnderline(Map map) {
//使用LinkedHashMap确保字段顺序一致性
LinkedHashMap transitionMap = new LinkedHashMap<>(16);
map.forEach((k, v) -> transitionMap.put(StrUtil.toUnderlineCase(k), v));
return transitionMap;
}
private void checkCreateTime(String startTime, String endTime) {
if ("".equals(startTime)) {
throw new RuntimeException("startTime cant be null");
}
if ("".equals(endTime)) {
throw new RuntimeException("endTime cant be null");
}
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm");
//Date monitorTime=null;
try {
sdf.parse(startTime);
sdf.parse(endTime);
//monitorTime=new Date(udate.getTime());
} catch (Exception e) {
throw new RuntimeException("日期格式必须yyyy-MM-dd HH:mm");
}
}
这里用到了hutool的包
import cn.hutool.core.util.StrUtil;
项目中还遇到了插入字段的顺序问题,我这里返回是LinkedHashMap来确保key顺序一致
3.mybatis配置驼峰
application配置
mybatis.configuration.map-underscore-to-camel-case=true
或者写mybatis-config.xml,效果一样
select返回字段数据如果为null,会出现返回map不存在该字段key的情况
假如我查的某一列有个字段为null,map会不返回,如下图
解决办法很简单,写一个mybatis-config.xml,加入该配置
在DBConfig里set进去该配置文件
@Bean
public MySqlSessionFactoryBean sqlSessionFactoryBean() throws Exception {
MySqlSessionFactoryBean sqlSessionFactoryBean = new MySqlSessionFactoryBean();
//加入本地config配置,确保转出的字段如果为null可以存在map内
Resource resources2 = new PathMatchingResourcePatternResolver().getResource("classpath:mybatis-config.xml");
sqlSessionFactoryBean.setConfigLocation(resources2);
return sqlSessionFactoryBean;
}
批量更新报SQLSyntaxError问题
我在做批量更新需求的时候遇到的一个坑,一直报错语法问题,但本地调试SQL没有任何问题,仔细查找后发现其实是mybatis不支持批量update操作
org.springframework.jdbc.BadSqlGrammarException: ### Error updating database. Cause: java.sql.SQLSyntaxErrorException: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'update mall_product
解决方案其实就是在jdbc配置url上加上如下配置
allowMultiQueries=true
配置文件跟上
db.url=jdbc:mysql://localhost:3306/test?allowMultiQueries=true&characterEncoding=utf8&serverTimezone=GMT
mybatis批量更新报错解决办法
mybatis invalid comparison: java.sql.Timestamp and java.lang.String错误代码:
AND a.update_date = #{updateDate}
修改后:
AND a.update_date = #{updateDate}
或者手工过滤,!=是datetime的字段



