文章目录
resultType
resultType:表示sql语句的执行结果,转换为的java对象模型,该属性值一般填写的是返回值类型的全限定名称,例如,返回值类型为Student时,resultType的值为com.example.entity.Student。示例项目的目录结构如下图所示:
除此之外,我们还可以使用别名(给Student类起别名);若使用别名,需要在mybatis主配置文件中定义别名,定义别名有两种方式(两种方式的根标签均为typeAliases
):
- 使用<typeAlias>
<typeAlias type="com.example.entity.Student" alias="stu"/>
其中,type的值为类的全限定名称(示例中类为Student),alias的值是给类(Student)自定义的名称,这时,resultType的值可以写为stu,即resultType="stu"
。
- 使用<package name=“包名”/>
<package name="com.example.entity"/>
name的值为类所在的包的包名,使用这种方式,该包下的所有类都起了别名,类名即是别名(不区分大小写)
。
resultMap
resultMap:自定义列名和java对象的属性名对应关系。
执行sql语句获取到结果后,默认情况下,会找到与数据库表中字段名相同的属性名,将获取的值赋值给该属性,例如,数据库表student中有四个字段,分别为id、name、email、age,Student类中的四个属性id、name、email、age与其一一对应。如果我们将Student中的name属性改名为myname,则获取到的结果显示name=null
,即最终获取结果没有找到对应的属性,面对这种情况,我们有两种方式解决:
- 使用resultMap
<resultMap id="studentMap" type="com.example.entity.Student">
<!-- 列名和java属性的关系 -->
<!-- 主键列使用id标签
column:数据库表中的字段名(列名)
property:java类型(Student)的属性名
-->
<id column="id" property="myid"/>
<!-- 非主键列,使用result -->
<result column="name" property="myname"/>
<result column="email" property="myemail"/>
<result column="age" property="myage"/>
</resultMap>
<select id="selectAllStudents" resultMap="studentMap">
select id, name, email, age from student
</select>
其中,resultMap的值为resultMap标签中id属性的值。
- 使用别名
通过给获取的字段取别名,也能够解决上述问题,示例如下:
<select id="selectAllStudents" resultType="com.example.entity.Student">
select id as stuid, name, email, age from student
</select>
上述例子中,给数据库表student中的id字段取了一个别名stuid,对应Student类中的stuid属性。