mybatis 从数据库中获取信息映射到实体中时,往往会遇到变量名带有下划线的情况,处理不好容易产生“o.a.i.s.AutoMappingUnknownColumnBehavior : Unknown column is detected on '*****' auto-mapping. Mapping parameters are [columnName=***_***,propertyName=***_***,propertyType=null]”,带有下划线的变量无法得到映射。
解决办法如下:
1.在mybatis设置文件中设置<setting name="mapUnderscoreToCamelCase" value="true"/>,启动驼峰规则,这样在map文件中带下划线的column会自动按照驼峰命名规则映射到实体属性变量中。
例如:
map文件中 select user_id, user_name from user_info where user_id=#{id}
resultType对应的bean中对应的变量名要使用userId 和userName 或者按照驼峰规则编写set方法
2.禁用驼峰规则<setting name="mapUnderscoreToCamelCase" value="false"/>,这样map文件中的带有下划线的columnName会一对一的对应到实体类中的同名变量中。
例如:
map文件中 select user_id, user_name from user_info where user_id=#{id}
resultType对应的bean中对应的变量名user_id和user_name
3.如果不想禁用驼峰规则,有不想修改实体类,那就在map文件中使用resultMap,resultMap中的columnName不受驼峰规则的影响,间接起到了禁用驼峰规则的效果。
例如:
<resultMap id="userResultMap" type="cn.**.User">
<result property="user_id" column="user_id"/>
<result property="user_name" column="user_name"/>
</resultMap>