Mybatis_resultMap

javaBean与sql返回的映射关系实现方式
1、全局配置文件中开启自动映射autoMappingBehavior配置
2、使用驼峰命名规则,开启驼峰命名映射mapUnderscoreToCamelCase设置
3、使用自定义映射resultMap

resultMap实现步骤
前提:全局配置文件中使用批量注册sql映射接口,测试中所有mapper接口均存放在com.taozi.mybatis.test包下,sql映射文件均存放在源码包的conf下的com.taozi.mybatis.test包下,测试类存放于源码的com.taozi.mybatis.proc包下。目录结构如下:
这里写图片描述

mysql中stu表结构

这里写图片描述

全局配置文件批量注册

<package name="com.taozi.mybatis.test"/>

sql映射接口

package com.taozi.mybatis.test;

import com.taozi.mybatis.bean.Student;

public interface Mybatis_mapper_04 {

    public Student getStuById(int id);

}

sql映射文件

<mapper  namespace="com.taozi.mybatis.test.Mybatis_mapper_04">

 <!-- 自定义javaBean的封装规则 -->
 <!-- 
     type:自定义规则的java类型
     id:唯一标识,供后续使用
  -->
 <!-- 这里的类名建议使用全类名,别名虽简单,但是不方便查阅 -->
 <resultMap type="com.taozi.mybatis.bean.Student" id="myStuMap">
    <!-- 主键列的封装规则 ,底层会有对应的优化,此处也可使用result-->
     <id column="id" property="id"/>
    <!-- 其他列的映射规则 -->
    <!--  <result column="Sex" property="gender"/>-->
    <result column="gender" property="Sex"/>
    <!-- 建议可以自动映射的字段也写在自定义映射map中,便于检查 -->
    <result column="name" property="name"/>
 </resultMap>

 <!-- public Student getStuById(int id); -->
 <select id="getStuById" resultMap="myStuMap" databaseId="mysql">
    select * from stu where id =#{id}
 </select>

 </mapper>

测试类

@Test
    public void test() throws IOException {

        String resource = "mybatis-config.xml";
        InputStream inputStream = Resources.getResourceAsStream(resource);
        SqlSessionFactory sqlSessionFactory =
                  new SqlSessionFactoryBuilder().build(inputStream);
        SqlSession session = sqlSessionFactory.openSession();

        Mybatis_mapper_04 mapper = session.getMapper(Mybatis_mapper_04.class);
        Student stu = mapper.getStuById(3);
        System.out.println(stu);

        session.close();
//      fail("Not yet implemented");
    }

输出结果

Student [id=3, name=tttt, sex=f]

小结:

resultMap中,result标签的column属性指的是库中表字段名称,property指的数自定义java类型中属性名称。

失败:<result column="Sex" property="gender"/>
    Student [id=3, name=tttt, sex=,sex属性为空
成功:<result column="gender" property="Sex"/>
    Student [id=3, name=tttt, sex=f],sex获取到gender的值
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值