resultMap: 可以手动配置表和对象之间的映射关系
将驼峰匹配注释掉
在映射文件XXX.xml中配置resultMap
< !--
resultMap标签:可以自己配置对象属性和表字段的映射(不仅仅是驼峰规则的映射)
type属性:结果集的封装类型
id属性:唯一标识
autoMapping属性:如果不配置,默认为true。对其他属性进行自动映射。
-->
<resultMap type="User" id="userResultMap" autoMapping="true">
<!-- id标签:配置主键映射,column:表中的字段名称,property:属性名称 -->
<id column="id" property="id"/>
<!-- 可以用来配置普通类型字段和属性映射(非复杂类型) -->
<result column="user_name" property="userName"/>
</resultMap>
在statement中引用自定义resultMap
<!-- resultMap:引用自定义结果集的唯一标识 -->
<select id="queryUserById" resultMap="userResultMap">
select * from tb_user where id = #{id}
</select>
resultMap中的autoMapping属性的值:
为true时:resultMap中的没有配置的字段会自动对应。如果不配置,则默认为true。
为false时:只针对resultMap中已经配置的字段作映射。
sql片段: 可以抽取重复使用的sql片段,如果单独设置了一个映射文件,那么该映射文件需要被mybatis-config.xml管理,并且引用方式:namespace.id
新建一个CommonSQL.xml:
<mapper namespace="CommonSQL">
<sql id="commonSql">
sql语句
</sql>
</mapper>
mybatis-config中引入映射文件:
<mapeer resource="CommonSQL.xml" />
在需要使用该sql片段的地方通过include标签的refId属性引用该sql片段:
<include refId=”CommonSQL.commonSql” />