SELECT id,name,pwd FROM user WHERE id=#{id};
mybatis会自动创建一个ResultMap来映射结果集
例如User类中包含属性 id,name,pwd,则自动映射,都能对应上
但如果User类中的属性字段为id,name,password,查询出的结果password = null
解决办法
1、SQL语句字段起别名
把对应的SQL语句改为
SELECT id,name,pwd as password FROM user WHERE id=#{id};
但这并不是一种好方法
2、使用ResultMap结果集来映射
<!--mybatis配置文件中使用TypeAlias配置了别名-->
<resultMap id="userResultMap" Type="User">
<!--column对应了数据库表中的字段名,property对应了实体类的属性名-->
<result column="id" property="id" />
<result column="name" property="name" />
<result column="pwd" property="password" />
</resultMap>
3、如果需要查的字段不是基本数据类型,而是一个对象(多表联查)
1)按照查询嵌套处理
<select id="getStudents" resultMap="StudentTeacher">
select s.id,s.name,t.name from student s,teacher t where s.tid=t.id
</select>
<resultMap id="StudentTeacher" Type="Student">
<!--字段是Student类的属性时-->
<result column="id" property="id" />
<result column="name" property="name" />
<!--复杂的属性需要单独处理
对象:association
集合:collection
子查询
-->
<association column="tid" property="teacher" javaType="Teacher" select="getTeacher"/>
</resultMap>
<select id="getTeacher" resultType="Teacher">
select * from teacher where tid=#{tid}
</select>
2)按照结果嵌套处理
多对一
<select id="getStudents" resultMap="StudentTeacher">
select s.id as sid,s.name as sname,t.name as tname
from student s,teacher t
where s.tid=t.id
</select>
<resultMap id="StudentTeacher" type="Student">
<result column="sid" property="id" />
<result column="sname" property="name" />
<association property="teacher" javaType="Teacher">
<result column="tname" property="name" />
</association>
</resultMap>
一对多,即Java类的属性字段里有List这样的集合
<select id="getTeacher" resultMap="TeacherStudents">
select s.id sid,s.name sname,t.id tid,t.name tname
from student s,teacher t
where s.tid=t.id and t.id=#{tid}
</select>
<resultMap id="TeacherStudents" type="Teacher">
<result column="tid" property="id" />
<result column="tname" property="name" />
<!--属性是集合时,使用collection-->
<!--javaType:指定属性的类型
集合中的泛型信息,使用ofType获取
-->
<collection property="students" ofType="Student">
<result column="sid" property="id" />
<result column="sname" property="name" />
<result column="tid" property="tid" />
</collection>
</resultMap>
总结:
1)属性中包含的是对象,使用association
2)属性中包含的是集合,使用collection
3)javaType 和 ofType的区别
javaType:属性字段的类型
ofType:集合中泛型的类型