目录
一 点睛
它是解决实体类属性名和数据库字段名不一致的问题。
二 构造实体类和数据库不一致
public class User {
private int id; // 数据库字段是id
private String name; // 数据库字段是name
private String password; // 数据库字段是pwd
}
测试出现问题
User{id=1, name='cakin', pwd='null'}
三 解决方法
1 起别名
<select id="getUser" resultType="com.cakin.pojo.User">
/*pwd起别名为password*/
select id,name,pwd as password from user where id = #{id}
</select>
2 resultMap
结果集映射
id name pwd
id name password
配置方法
<!--结果集映射-->
<resultMap id="UserMap" type="com.cakin.pojo.User">
<!--column数据库的字段,property实体类中的属性-->
<result column="pwd" property="password" />
<!--因为数据库字段和属性一致,下面两个可以不配置-->
<result column="id" property="id" />
<result column="name" property="name" />
</resultMap>
<!--查-->
<select id="getUser" resultMap="UserMap">
select * from user where id = #{id}
</select>
resultMap元素是MyBatis中最重要最强大的元素。
ResultMap设计的思想是,对于简单的语句根本不需要配置显示的结果映射,而对于复杂一点的语句只需要描述它们的关系就行了。
ResultMap最优秀的地方在于,虽然你已经对它相当了解了,但是根本就不需要显示地调用他们。