一、编写SQL的XML映射文件
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<!-- 为这个mapper指定一个唯一的namespace,namespace的值习惯上设置成包名+sql映射文件名,这样就能够保证namespace的值是唯一的 -->
<mapper namespace="com.mapping.teacherMapper">
<!--
根据tid查询得到一个teacher对象,使用这个查询是查询不到我们想要的结果的,
这主要是因为实体类的属性名和数据库的字段名对应不上的原因,因此无法查询出对应的记录
-->
<select id="getTeacherById" parameterType="int"
resultType="com.domain.Teacher">
select * from ksl_teacher where tid=#{tid}
</select>
<!--
根据tid查询得到一个teacher对象,使用这个查询是可以正常查询到我们想要的结果的,
这是因为我们将查询的字段名都起一个和实体类属性名相同的别名,这样实体类的属性名和查询结果中的字段名就可以一一对应上
-->
<select id="selectTeacher" parameterType="int"
resultType="com.domain.Teacher">
select tid id, tname name from ksl_teacher where tid=#{tid}
</select>
<!--
根据tid查询得到一个teacher对象,使用这个查询是可以正常查询到我们想要的结果的,
这是因为我们通过<resultMap>映射实体类属性名和表的字段名一一对应关系 -->
<select id="selectTeacherResultMap" parameterType="int" resultMap="teacherResultMap">
select * from ksl_teacher where tid=#{tid}
</select>
<!--通过<resultMap>映射实体类属性名和表的字段名对应关系 -->
<resultMap type="com.domain.Teacher" id="teacherResultMap">
<!-- 用id属性来映射主键字段 -->
<id property="id" column="tid"/>
<!-- 用result属性来映射非主键字段 -->
<result property="name" column="tname"/>
</resultMap>
</mapper>
二、在conf.xml中注册xml映射文件
<mapper resource="com/mapping/teacherMapper.xml"/>
三、编写单元测试代码
public class Test2 {
@Test
public void testGetTeacherById() {
SqlSession sqlSession = MyBatisUtil.getSqlSession(true);
String statement = "com.mapping.teacherMapper.getTeacherById";
Teacher t = sqlSession.selectOne(statement, 1);
sqlSession.close();
System.out.println(t);
}
@Test
public void testGetTeacherById2() {
SqlSession sqlSession = MyBatisUtil.getSqlSession(true);
String statement = "com.mapping.teacherMapper.selectTeacher";
Teacher t = sqlSession.selectOne(statement, 2);
sqlSession.close();
System.out.println(t);
}
@Test
public void testGetTeacherById3() {
SqlSession sqlSession = MyBatisUtil.getSqlSession(true);
String statement = "com.mapping.teacherMapper.selectTeacherResultMap";
Teacher t = sqlSession.selectOne(statement, 3);
sqlSession.close();
System.out.println(t);
}
}
执行单元测试的结果:
1.testGetTeacherById方法返回null;
2.testGetTeacherById2和testGetTeacherById3方法可以正常得到想要的结果。
四、总结
上面的测试代码演示了当实体类中的属性名和表中的字段名不一致时,使用MyBatis进行查询操作时无法查询出相应结果的问题以及针对问题的两种解决方法:
1.通过在查询的SQL语句中定义字段名的别名,让字段名的别名与实体类的属性名一致,这样就可以让表的字段名与实体类的属性名一一对应上了,这种方式是通过在SQL语句中定义别名来解决字段名和属性名的映射关系的;
2.通过<resultMap>来映射字段名和属性名,这种方式是使用MyBatis提供的解决方式。
转载于:https://www.cnblogs.com/yuanfei1110111/p/10349811.html