当实体类的属性名和数据库表的字段名称不同时,如何实现数据库的对应操作,有两种解决方式;
通过设置别名的方式:
例如:数据库表student的字段为tid,tname,tage,score
而对应的实体类的属性名为id,name,age,score
此时我们可以通过在写SQL语句时设置别名
<mapper namespace="xxx">
<select id="selectAllStudent" resultType="com.mybatis.beans.Student">
select tid id,tname name,tage age,score from student
</select>
<select id="selectStudentById" resultType="com.mybatis.beans.Student">
select tid id,tname name,tage age,score from student where tid=#{id}
</select>
</mapper>
通过使用<resultMap>标签
<mapper namespace="xxx">
<!--通过设置resultMap的值,将字段名和属性名一一对应起来-->
<resultMap type="com.mybatis.beans.Student" id="studentMap">
<id column="tid" property="id"/>
<result column="tname" property="name"/>
<result column="tage" property="age"/>
</resultMap>
<!--通过调用resultMap将字段名转化成属性名并封装成student对象-->
<select id="selectAllStudent" resultMap="studentMap">
select tid,tname,tage,score from student
</select>
<select id="selectStudentById" resultMap="studentMap">
select tid,tname,tage,score from student where tid=#{id}
</select>
</mapper>