[刘阳Java]_MyBatis_其他方式来实现多表查询的操作_第9讲

MyBatis其他方式来实现多表查询的操作

  • 利用Java中的集合框架(List,Map)
  • 其中List存储多个查询返回的记录
  • Map查询返回字段,同时记录表中一条数据
<?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">
<mapper namespace="com.gxa.mapper.StudentMapper_2">

    <select id="getStudent" resultType="java.util.HashMap">
        SELECT sid,sname,a.t_id,t_name FROM student a, teacher b WHERE a.t_id=b.t_id
    </select>
    
</mapper>
package com.gxa.test;

import java.io.IOException;
import java.io.Reader;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

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 org.junit.Test;

import com.gxa.pojo.Student;
import com.gxa.pojo.Teacher;
import com.gxa.pojo.Team;

public class Test03 {
    private static SqlSessionFactorysqlSessionFactory;
    private static Reader reader;
    
    static {
        try {
            reader = Resources.getResourceAsReader("config.xml");
            sqlSessionFactory = new SqlSessionFactoryBuilder().build(reader);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    
    @Test
    public void m01() {
        SqlSessionsqlSession = sqlSessionFactory.openSession();
        String sql = "com.gxa.mapper.StudentMapper.getStudent";
        List<Student> list = sqlSession.selectList(sql);
        for (Student student : list) {
            System.out.println(student.getSname() + "====" + student.getTeacher().getT_name());
        }
        sqlSession.close();
    }
    
    @Test
    public void m02() {
        SqlSessionsqlSession = sqlSessionFactory.openSession();
        String sql = "com.gxa.mapper.TeacherMapper.getTeacher";
        Teacher teacher = sqlSession.selectOne(sql);
        List<Student> student = teacher.getStudent();
        for (Student s : student) {
            System.out.println(teacher.getT_name() + "===" + s.getSname());
        }
        sqlSession.close();
    }
    
    @Test
    public void m03() {
        SqlSessionsqlSession = sqlSessionFactory.openSession();
        String sql = "com.gxa.mapper.StudentMapper_2.getStudent";
        List<Map<String, Object>> list = sqlSession.selectList(sql);
        System.out.println(list);
        sqlSession.close();
    }
    
}

 

posted @ 2017-03-27 16:17  子墨老师  阅读(512)  评论(0编辑  收藏  举报