5.ResultMap结果映射(用于解决属性名和字段名不一致的问题)
-
resultMap元素是 MyBatis 中最重要最强大的元素。 -
ResultMap 的设计思想是,对简单的语句做到零配置,对于复杂一点的语句,只需要描述语句之间的关系就行了。
第一种解决方法:起别名(as)
-
前者是数据库字段后者是实体类
-
<select id="selectUsers" resultType="User">
select
user_id as "id",
user_name as "userName",
hashed_password as "hashedPassword"
from some_table
where id = #{id}
</select>
第二种解决方法:ResultMap
-
数据库中为id,name,email,phone
-
//username,myemail,telephone这是我修改的三个属性
private Integer id;
private String username;
private String myemail;
private String telephone; -
于是我们需要在UserMapper.xml配置文件中修改
-
id指定唯一标识 type指定结果集映射 返回的是User对象
-
<!--property对应的是实体类的属性 column对应的是数据库的字段-->
<resultMap id="userResultMap" type="User">
<id property="id" column="id"></id>
<result property="username" column="name"></result>
<result property="myemail" column="email"></result>
<result property="telephone" column="phone"></result>
</resultMap> -
这是select语句 可以发现resultMap为上面的id属性值(注意我们去掉了
resultType属性) -
<!--通过id查询一个user对象-->
<select id="findById" parameterType="Integer" resultMap="userResultMap">
select * from user where id=#{id}
</select> -

浙公网安备 33010602011771号