MyBatis的resultMap


一、介绍

  • 为了解决数据库字段列名和返回值POJO类属性不一致的问题,除了别名方式还可以使用resultMap

二、单表

1、接口

List<User> queryAll();

2、xml

<!-- id:节点的唯一标识(自定义);type:返回的数据类型 -->
<resultMap id="userResult" type="com.User">
    <!-- id:具有自增长的特性的主键类型,用该id标签;result:其它的普通属性用该标签 -->
    <!-- column:数据库字段;property:数据库字段映射的实体类属性 -->
    <id column="user_id" property="userId" />
    <result column="user_name" property="userName"  />
</resultMap>

<select id="queryAll"  resultMap="userResult">
	select id,user_name from t_user
</select>

三、关联查询

1、接口

List<DeptVO> findAllByDeptno(Integer deptId);

2、xml

<resultMap id="deptVoMap"  type="vo.DeptVO">
    <id column="dep_id"      property="deptId"/>
    <result column="name"  property="deptName"/>
    <!-- collection:属性是集合类型用该标签;ofType:集合的泛型的数据类型 -->
    <collection property="users"  ofType="user.User">
        <!-- 自此开始,column表示t_user表字段;property表示User中的属性 -->
        <id column="id" property="id"/>
        <result column="username" property="username"/>
        <result column="password" property="password"/>
        <result column="dept_id" property="deptId"/>
	</collection>
</resultMap>

<select id="queryAllByDeptId" resultMap="deptVoMap">
    select
    	dept.id dep_id,
    	dept.name,
    	user.id,
    	user.username,
    	user.password,
    	user.dept_id
    from t_user user
    join t_dept dept on user.dept_id=dept.id
    where t_dept.id=#{deptId}
</select>

3、返回值

{
    "deptId":2,
    "deptName":"c++",
    "users":[
        {
            "id":13,
            "username":"spring",
            "password":"1234",
            "deptId":2
        },
        {
            "id":14,
            "username":"mybatis",
            "password":"12cxv34",
            "deptId":2
        }
    ]
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

kimi-001

只想在有限的时间分享更多的知识

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值