目前在做mybatis数据迁移的时候遇到了不少坑,以前项目没有配置项,导致会产生不少bug,目前记录排坑了三种场景和其解决方案
之前项目中没引入,解决办法有三个:
1.手工转,字段多的话很麻烦
<select id="lzqQuery" resultType="com.lzq.lzqEntity"
parameterType="java.util.HashMap">
select
id as id
,store_id as storeId
from xxx
</select>
2.外面写方法转
/**
* 把 map 中的 key 由驼峰命名转为下划线,使用LinkedHashMap确保字段顺序一致性
*/
private LinkedHashMap<String, Object> humpToUnderline(Map<String, Object> map) {
//使用LinkedHashMap确保字段顺序一致性
LinkedHashMap<String, Object> 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,效果一样
<setting name="mapUnderscoreToCamelCase" value="true"/>

假如我查的某一列有个字段为null,map会不返回,如下图

解决办法很简单,写一个mybatis-config.xml,加入该配置
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config 3.0//EN" "http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
<settings>
<setting name="callSettersOnNulls" value="true"/>
</settings>
</configuration>
在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;
}
我在做批量更新需求的时候遇到的一个坑,一直报错语法问题,但本地调试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
错误代码:
<if test="updateDate != null&&updateDate!=''">
AND a.update_date = #{updateDate}
</if>
修改后:
<if test="updateDate != null">
AND a.update_date = #{updateDate}
</if>
或者手工过滤,!=是datetime的字段