springboot-mybatis数据库字段和实体字段名称不一致,查询值为null
一、问题和原因
java默认开启驼峰模式的字段,但数据库字段部分带下划线开头,会被转换大小写
如:
数据库:Pallet_ID
实体:Pallet_ID
查询的数据 :pallet_ID(大小写被自动转了,所以该字段一直为null)。
所以是设置的驼峰格式导致的字段格式与数据库不一致导致的。
就是springboot的application.yml里的这段,但是这个一般不能关
configuration:
map-underscore-to-camel-case: true
二、我的解决,总结参考了:https://www.cnblogs.com/yif0118/p/14601572.html
有三种方法
2.1.查询的sql语句中使用别名进行查询
2.2.使用resultMap映射实体
<resultMap id="deptMap" type="dept">
<!-- property: 实体类属性名.
column: 库中表的列名
javaType: 数据类型.
-->
<id property="deptno" column="deptno" javaType="long"></id>
<result property="dname" column="dname"></result>
<result property="dbSource" column="db_source"></result>
</resultMap>
<select id="queryById" parameterType="long" resultMap="deptMap">
select * from springcloud_db01.dept where deptno = #{deptno}
</select>
2.3 修改配置文件
在springboot的application.yml不能同时使用以下两个配置,换句话说,两者配置方式只能取其一.
正确方式一:
mybatis:
# 指定全局配置文件位置
config-location: classpath:mybatis/mybatis-config.xml
# 指定sql映射文件位置
mapper-locations: classpath:mybatis/mapper/*.xml
正确方式二:指定sql映射文件位置
mybatis:
mapper-locations: classpath:mybatis/mapper/*.xml
configuration:
map-underscore-to-camel-case: true
以上两种方法是我抄的,我最后是这么解决的,我的不是冲突而是配置写的不对,缺个参数,mybatis.mapper-locations的classpath没写mybatis
正确写法:
mybatis.type-aliases-package=cn.codesheep.springbt_mybatis_sqlserver.entity
mybatis.mapper-locations=classpath:mybatis/mapper/*.xml
mybatis.configuration.map-underscore-to-camel-case=false