MyBatis學習(五)resultMap測試

resultMap是MyBatis最強大的元素,它的做用是告訴MyBatis將從結果集中取出的數據轉換成開發者所須要得對象。java

接下來咱們對resultMap進行一個簡單測試。(當所須要返回的對象是一個對象關聯到另外一個對象的結果時)mysql

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.xmlsql

<?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.javaapache

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();
    }
}

運行後能夠在控制檯看到以下結果:session

源碼下載路徑:https://files.cnblogs.com/files/dj-blog/resultMapest.zipmybatis

相關文章
相關標籤/搜索