首页 /  技术专区  /  Mybatis 宽屏模式 >

Mybatis:resultMap结果集映射

1、解决字段名和属性名不一样的问题

数据库中的字段:

image.png

新建一个项目,拷贝之前的,测试实体类字段不一致的情况。

public class User {

    private int id;
    private String name;
    private String password;
}

测试出现问题:

image.png

select * from mybatis.user where id = #{id};
//类型处理器
select id, name, pwd from mybatis.user where id = #{id};

解决方法:

起别名

select id, name, pwd as password from mybatis.user where id = #{id};

2、resultMap

<!-- 结果集映射 -->
<resultMap id="userMap" type="com.allen.pojo.User">
    <!-- column数据库中的字段,property实体中的属性 -->
    <result column="id" property="id" />
    <result column="name" property="name" />
    <result column="pwd" property="password" />
</resultMap>

<select id = "getUserById" resultMap="userMap" parameterType = "int">
    select * from mybatis.user where id = #{id};
</select>

resultMap元素是MyBatis中最重要最强大的元素

resultMap的设计思想是,对于简单的语句根本不需要配置显式的结果映射,而对于复杂一点的语句只需要描述它们的关系就行了。

resultMap最优秀的地方在于,虽然你已经对它相当了解了,但是根本就不需要显式地用到他们。

如果世界总是这么简单就好了。




头像
0/200
图片验证码