Mybatis概述
Mybatis是目前比较经典的一个持久层框架,也是大部分初学者所接触的第一个持久层框架,在单纯使用Mybatis而不使用SpringBoot等整合框架的时候,往往需要自己配置XML文件,在平时配置XML文件的时候就会经常使用到paramaterType、parameterMap、resultType、resultMap, 如下。
<select resultMap="ResultMap" parameterType="int">
select * from student where id=#{studentId}
</select>
paramaterType
这是一段用于向数据库通过指定id查询某个学生的代码,parameterType用于表明传入参数的类型,由于id是int类型,所以这里parameter指定是int,也可以用的形式来指定。
parameterMap
parameterMap可以用于指定实体类字段属性与数据库字段属性的映射关系,可以和esult Map搭配使用,例如:
<parameterMap type="Student">
<parameter property="studentId" resultMap="ResultMap"></parameter>
<parameter property="studentName" resultMap="ResultMap"></parameter>
<parameter property="studentAge" resultMap="ResultMap"></parameter>
</parameterMap>
<resultMap type="Student">
<id column="id" property="studentId"></id>
<result column="name" property="studentName"></result>
<result column="age" property="studentAge"></result>
</resultMap>
这样一来当传入参数实体类中的字段名和数据库的字段名名称上没有对应也能查询出想要的结果,这就是parameterMap的作用。
resultType
resultType用于指定数据查询结果要封装的实体类对象,也就是指明返回类型。如下:
<select resultType="">
select * from student
</select>
这样一来,这条执行语句所返回的结果就会封装到Student这个实体类中,但是此处查询结果集到Student对象的映射关系是固定的,只有列名和属性名相同,该结果集才能封装成功。
resultMap
ResultMap:将查询结果集中的列一一映射到实体类的各个属性上去,此处的这个映射关系,可以根据我们在“resultMap”的子标签中的配置来决定的,灵活多变,常用于多表查询以及查询时使用别名的情况。
ResultMap标签及其子标签部分属性:
属性 | 作用 |
---|---|
id | 指定查询结果集中的唯一标识,即主键,可配置多个 |
column | 查询结果集中的列名,要和数据库字段名对应 |
property | 和数据库字段对应的实体类的字段名 |
示例代码
<resultMap type="Student">
<id column="id" property="studentId"></id>
<result column="name" property="studentName"></result>
<result column="age" property="studentAge"></result>
</resultMap>