属性:
id:该封装规则的唯一标识
type:封装出来的类型,可以是jdk自带的,比如Map,应该可以是自定义的,比如Employee
autoMapping:自动封装,如果数据库字段和javaBean的字段名一样,可以使用这种方式,但是不建议采取,还是老老实实写比较稳妥,如果非要使用此功能,那就在全局配置中加上mapUnderscoreToCamelCase=TRUE,它会使经典数据库字段命名规则翻译成javaBean的经典命名规则,如:a_column翻译成aColumn
extends:继承其他封装规则,和Java中的继承一样,也特别适合这样的场景
子标签:
id
用来标识出对象的唯一性,比如用表的主键,如:
<id column="employee_id" property="empId"/>
column指定数据库字段名或者其别名
property指定javaBean的属性名
还有jdbcType,javaType,typeHandler,分别数据库类型,属性的java类型,数据库与Java类型匹配处理器
默认的类型匹配处理器有:
result
非主键的映射规则
<result column="dept_name" property="deptName"/>
association
属性:
property:同id标签
javaType:同id标签
select:指定嵌套SQL,可以是本XML或者其他XML文件中的select标签
fetchType:延迟加载,lazy打开延迟加载;eager积极加载
column:同id标签
resultMap:不使用嵌套SQL,而是使用复杂SQL一次取出关联的对象,并封装,对应下面的方式三
resultSet:引用根据select标签得到的resultSets,如:
SELECT * FROM BLOG WHERE ID = #{id}
SELECT * FROM AUTHOR WHERE ID = #{id}
<select id="selectBlog" resultSets="blogs,authors" resultMap="blogResult" statementType="CALLABLE">
{call getBlogsAndAuthors(#{id,jdbcType=INTEGER,mode=IN})}
</select>
<resultMap id="blogResult" type="Blog">
<id property="id" column="id" />
<result property="title" column="title"/>
<association property="author" javaType="Author" resultSet="authors" column="author_id" foreignColumn="id">
<id property="id" column="id"/>
<result property="username" column="username"/>
<result property="password" column="password"/>
<result property="email" column="email"/>
<result property="bio" column="bio"/>
</association>
</resultMap>
autoMapping:同id标签
columnPrefix:关联多张表查询时,为了使列明不重复,使用此功能可以减少开发量
<select id="selectBlog" resultMap="blogResult">
select
B.id as blog_id,
B.title as blog_title,
A.id as author_id,
A.username as author_username,
A.password as author_password,
A.email as author_email,
A.bio as author_bio,
CA.id as co_author_id,
CA.username as co_author_username,
CA.password as co_author_password,
CA.email as co_author_email,
CA.bio as co_author_bio
from Blog B
left outer join Author A on B.author_id = A.id
left outer join Author CA on B.co_author_id = CA.id
where B.id = #{id}
</select>
抽取出共同的resultMap,因为作者和其他作者都具有同样的属性,因此有:
<resultMap id="authorResult" type="Author">
<id property="id" column="author_id"/>
<result property="username" column="author_username"/>
<result property="password" column="author_password"/>
<result property="email" column="author_email"/>
<result