• 列名与属性名不一致


    【概述】

    实际编写代码时,常会出现列名和对象的属性名不一致的情况.MyBatis通过ResultMap提供了解决方案。

     

    【表结构】

    【实体类】

    public class User {

    private int id;

    private String account;

    private String name;

    private String password;

    private int age;

    private boolean gender;

       ......

    }

    【方式一:列别名方式】

    1     <select id="getAll1" resultType="cn.hl.vo.User">
    2         <!-- 1、通过查询语句进行解决:使用列别名 -->
    3         select userId as id, userName as name,account, pwd as password, age,gender from users
    4     </select>
     1     @Test
     2     public void test2() throws IOException{
     3         //1、加载配置文件
     4         Reader reader = Resources.getResourceAsReader("conf.xml");
     5         //2、获取SqlSessionFactory对象
     6         SqlSessionFactory fac =new SqlSessionFactoryBuilder().build(reader);
     7         //3、获取SqlSession对象
     8         SqlSession session = fac.openSession();
     9         
    10         List<User> list = session.selectList("cn.hl.vo.User.getAll1");
    11         session.close();
    12         
    13         System.out.println(list);
    14         
    15     }

    【方式二:ResultMap】

     1     <select id="getAll2" resultMap="UserMap">
     2         <!-- 2、通过resultMap进行配置 -->
     3         select * from users
     4     </select>
     5     
     6     <!-- 
     7         配置返回数据的类型
     8             type    :查询结果的返回值类型
     9             id        :resultMap的Id
    10     -->
    11     <resultMap type="cn.hl.vo.User" id="UserMap">
    12         <!-- 一般用于主键列。column:用于配置表中列的名称;property:用于配置相匹配的对象的属性名 -->
    13         <id column="userId" property="id"/>
    14         <!-- 一般用于配置非主键列 -->
    15         <result  column="userName" property="name"/>
    16         <result column="pwd" property="password"/>
    17     </resultMap>
     1     @Test
     2     public void test3() throws IOException{
     3         //1、加载配置文件
     4         Reader reader = Resources.getResourceAsReader("conf.xml");
     5         //2、获取SqlSessionFactory对象
     6         SqlSessionFactory fac =new SqlSessionFactoryBuilder().build(reader);
     7         //3、获取SqlSession对象
     8         SqlSession session = fac.openSession();
     9         
    10         List<User> list = session.selectList("cn.hl.vo.User.getAll2");
    11         session.close();
    12         
    13         System.out.println(list);
    14         
    15     }
  • 相关阅读:
    www.a.shifen.com
    gstack pstack strace
    性能分析 函数粒度 函数里的一条语句 汇编 反编译 机器指令 %rbx,%rbp
    taocrypt
    sign
    Python 3.8.0 final¶ Release date: 2019-10-14
    超线程
    Python classes to extract information from the Linux kernel /proc files.
    借助中间件优化代码 将请求RequestId在服务端接收到请求在处理业务逻辑之前生成
    JVM CPU Profiler技术原理及源码深度解析
  • 原文地址:https://www.cnblogs.com/zhzcode/p/9889713.html
Copyright © 2020-2023  润新知