• MyBatis学习(五)resultMap测试


    resultMap是MyBatis最强大的元素,它的作用是告诉MyBatis将从结果集中取出的数据转换成开发者所需要得对象。

    接下来我们对resultMap进行一个简单测试。(当所需要返回的对象是一个对象关联到另一个对象的结果时)

    1.创建一个项目,导入所需的jar包,在src目录下加入两个属性文件db.properyies和log4j.properties。

    2.创建两个表,编写两个实体类分别映射这两张表。

    -- Table structure for `t_student`
    -- ----------------------------
    DROP TABLE IF EXISTS `t_student`;
    CREATE TABLE `t_student` (
      `id` int(11) NOT NULL AUTO_INCREMENT,
      `name` varchar(18) NOT NULL,
      `sex` varchar(3) NOT NULL,
      `age` int(11) NOT NULL,
      `cid` int(11) NOT NULL,
      PRIMARY KEY (`id`),
      KEY `cid` (`cid`),
      CONSTRAINT `cid` FOREIGN KEY (`cid`) REFERENCES `t_clazz` (`id`)
    ) ENGINE=InnoDB AUTO_INCREMENT=4 DEFAULT CHARSET=utf8;
    
    -- ----------------------------
    -- Records of t_student
    -- ----------------------------
    INSERT INTO `t_student` VALUES ('1', '张三', '', '11', '1');
    INSERT INTO `t_student` VALUES ('2', '李四', '', '12', '2');
    INSERT INTO `t_student` VALUES ('3', '小红', '', '13', '1');
    -- ----------------------------
    -- Table structure for `t_clazz`
    -- ----------------------------
    DROP TABLE IF EXISTS `t_clazz`;
    CREATE TABLE `t_clazz` (
      `id` int(11) NOT NULL,
      `code` varchar(18) NOT NULL,
      PRIMARY KEY (`id`)
    ) ENGINE=InnoDB DEFAULT CHARSET=utf8;
    
    -- ----------------------------
    -- Records of t_clazz
    -- ----------------------------
    INSERT INTO `t_clazz` VALUES ('1', '一班');
    INSERT INTO `t_clazz` VALUES ('2', '二班');
    public class Student {
    
        private Integer id;
        private String name;
        private String sex;
        private Integer age;
        //关联的clazz对象
        private Clazz clazz;
            //省略get、set、toString方法
    public class Clazz {
    
        private Integer id;
        private String code;
        //省略get、set、toString方法

    3.编写mybatis-config.xml和SQL映射文件

    mybatis-config.xml

    <?xml version="1.0" encoding="UTF-8"?>
    <!DOCTYPE configuration
      PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
      "http://mybatis.org/dtd/mybatis-3-config.dtd">
     <configuration>
         <!-- 引入 外部db.properties文件-->
         <properties resource="db.properties"/>
         <!-- 指定 MyBatis 所用日志的具体实现-->
         <settings>
             <setting name="logImpl" value="log4j"/>
         </settings>
         <!-- 环境配置 -->
         <environments default="mysql">
             <environment id="mysql">
                 <!-- 指定事务类型 -->
                 <transactionManager type="JDBC"/>
                     <!--  dataSource指数据源配置,POOLED是JDBC连接对象的数据源连接池的实现。 -->
                 <dataSource type="POOLED">
                     <property name="driver" value="${driver}"/>
                     <property name="url" value="${url}"/>
                     <property name="username" value="${username}"/>
                     <property name="password" value="${password}"/>
                 </dataSource>
             </environment>
         </environments>
         <!-- SQL映射文件位置 -->
         <mappers>
             <mapper resource="com/dj/mapper/StudentMapper.xml"/>
         </mappers>
     </configuration>

    StudetMapper.xml

    <?xml version="1.0" encoding="UTF-8"?>
    <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" 
    "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
    
    <!-- namespace指用户自定义的命名空间 -->
    <mapper namespace="com.dj.mapper.StudentMapper">
        <!-- 映射学生对象的resultMap -->
        <resultMap type="com.dj.domain.Student" id="studentResultMap">
            <id  property="id" column="id"/>
            <id property="name" column="name"/>
            <id property="sex" column="sex"/>
            <id property="age" column="age"/>
            <!-- 关联映射
                property:表示返回类型student的属性名 clazz
                column:表示数据库的列名
                javaType:表示property属性对应的类型名称
                select:表示执行一条查询语句,将查询到的结果封装到property所代表的类型对象中。
             -->
            <association property="clazz" column="cid" 
                    javaType="com.dj.domain.Clazz" select="selectClazzById"/>
        </resultMap>
        <select id="selectClazzById" resultType="com.dj.domain.Clazz">
            select * from t_clazz where id=#{id}
        </select>
        <select id="selectStudent" resultMap="studentResultMap">
            select * from t_student
        </select>
    </mapper>

    4.进行测试,在控制台输出从数据库查询到的学生信息

    StudentTest.java

    package com.dj.test;
    
    import java.io.IOException;
    import java.io.InputStream;
    import java.util.Iterator;
    import java.util.List;
    
    import org.apache.ibatis.io.Resources;
    import org.apache.ibatis.session.SqlSession;
    import org.apache.ibatis.session.SqlSessionFactory;
    import org.apache.ibatis.session.SqlSessionFactoryBuilder;
    
    import com.dj.domain.Student;
    
    public class StudentTest {
        
        public static void main(String[] args) throws IOException {
            InputStream inputStream = Resources.getResourceAsStream("mybatis-config.xml");
            SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
            SqlSession sqlSession = sqlSessionFactory.openSession();
            List<Student> list  = sqlSession.selectList("com.dj.mapper.StudentMapper.selectStudent");
            for (Student student : list) {
                System.out.println(student);
            }
            sqlSession.commit();
            sqlSession.close();
        }
    }

    运行后可以在控制台看到如下结果:

    源码下载路径:https://files.cnblogs.com/files/dj-blog/resultMapest.zip

  • 相关阅读:
    python 序列应用
    跨浏览器本地存储框架(store.js/USTORE.js/Box.js)
    【设计开发命名必备】英语单词缩写规则
    Web服务器性能估算
    Spring整合FreeMarker本地化动态设置
    mybatis注解详解
    两种Freemarker模板路径设置方法
    Drools5集成Spring3
    Oracle 时间戳生成语句(秒级+毫秒级)
    Drools动态加载规则文件
  • 原文地址:https://www.cnblogs.com/dj-blog/p/7563037.html
Copyright © 2020-2023  润新知