mybatis(八)mapper映射文件配置之select、resultMap

拥有回忆 提交于 2019-12-04 06:34:47

上篇介绍了insert、update、delete的用法,本篇将介绍select、resultMap的用法。select无疑是我们最常用,也是最复杂的,mybatis通过resultMap能帮助我们很好地进行高级映射。下面就开始看看select 以及 resultMap的用法:

先看select的配置吧:


<select
        <!--  1. id (必须配置)
        id是命名空间中的唯一标识符,可被用来代表这条语句。 
        一个命名空间(namespace) 对应一个dao接口, 
        这个id也应该对应dao里面的某个方法(相当于方法的实现),因此id 应该与方法名一致  -->
     
     id="selectPerson"
     
     <!-- 2. parameterType (可选配置, 默认为mybatis自动选择处理)
        将要传入语句的参数的完全限定类名或别名, 如果不配置,mybatis会通过ParameterHandler 根据参数类型默认选择合适的typeHandler进行处理
        parameterType 主要指定参数类型,可以是int, short, long, string等类型,也可以是复杂类型(如对象) -->
     parameterType="int"
     
     <!-- 3. resultType (resultType 与 resultMap 二选一配置)
         resultType用以指定返回类型,指定的类型可以是基本类型,可以是java容器,也可以是javabean -->
     resultType="hashmap"
     
     <!-- 4. resultMap (resultType 与 resultMap 二选一配置)
         resultMap用于引用我们通过 resultMap标签定义的映射类型,这也是mybatis组件高级复杂映射的关键 -->
     resultMap="personResultMap"
     
     <!-- 5. flushCache (可选配置)
         将其设置为 true,任何时候只要语句被调用,都会导致本地缓存和二级缓存都会被清空,默认值:false -->
     flushCache="false"
     
     <!-- 6. useCache (可选配置)
         将其设置为 true,将会导致本条语句的结果被二级缓存,默认值:对 select 元素为 true -->
     useCache="true"
     
     <!-- 7. timeout (可选配置) 
         这个设置是在抛出异常之前,驱动程序等待数据库返回请求结果的秒数。默认值为 unset(依赖驱动)-->
     timeout="10000"
     
     <!-- 8. fetchSize (可选配置) 
         这是尝试影响驱动程序每次批量返回的结果行数和这个设置值相等。默认值为 unset(依赖驱动)-->
     fetchSize="256"
     
     <!-- 9. statementType (可选配置) 
         STATEMENT,PREPARED 或 CALLABLE 的一个。这会让 MyBatis 分别使用 Statement,PreparedStatement 或 CallableStatement,默认值:PREPARED-->
     statementType="PREPARED"
     
     <!-- 10. resultSetType (可选配置) 
         FORWARD_ONLY,SCROLL_SENSITIVE 或 SCROLL_INSENSITIVE 中的一个,默认值为 unset (依赖驱动)-->
     resultSetType="FORWARD_ONLY">



配置看起来总是这么多,不过实际常用的配置也就那么几个, 根据自己的需要吧,上面都已注明是否必须配置。

下面还是上个demo及时练练手吧:

------------------------------------------------------------------------下面是针对select 的练手demo---------------------------------------------------------------------------------------

数据库:新增两张表(course, studentNew)


DROP TABLE IF EXISTS `course`;
CREATE TABLE `course` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `name` varchar(255) DEFAULT NULL,
  `deleteFlag` int(11) DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=6 DEFAULT CHARSET=utf8;

-- ----------------------------
-- Records of course
-- ----------------------------
INSERT INTO `course` VALUES ('1', '市场营销', '1');
INSERT INTO `course` VALUES ('2', '国际贸易', '0');
INSERT INTO `course` VALUES ('3', '网页设计', '0');
INSERT INTO `course` VALUES ('4', '计算机应用', '0');
INSERT INTO `course` VALUES ('5', '网络操作系统', '0');

-- ----------------------------
-- Table structure for `studentnew`
-- ----------------------------
DROP TABLE IF EXISTS `studentnew`;
CREATE TABLE `studentnew` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `name` varchar(255) DEFAULT NULL,
  `idcard` int(11) DEFAULT NULL,
  `courseid` int(11) DEFAULT NULL,
  `deleteflag` int(11) DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=18 DEFAULT CHARSET=utf8;

-- ----------------------------
-- Records of studentnew
-- ----------------------------
INSERT INTO `studentnew` VALUES ('10', '张三', '20140101', '1', '0');
INSERT INTO `studentnew` VALUES ('11', '张三', '20140101', '2', '0');
INSERT INTO `studentnew` VALUES ('12', '张三', '20140101', '3', '0');
INSERT INTO `studentnew` VALUES ('13', '李四', '20140102', '2', '0');
INSERT INTO `studentnew` VALUES ('14', '王五', '20140103', '3', '0');
INSERT INTO `studentnew` VALUES ('15', '王五', '20140103', '5', '0');
INSERT INTO `studentnew` VALUES ('16', '张小虎', '20140104', '4', '0');
INSERT INTO `studentnew` VALUES ('17', '赵子龙', '20140105', '4', '0');



其中,1个student可选择多个course进行学习。

我们还是拿上篇文章的demo, 继续写:

增加后,项目目录如下所示:


courseDao.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">

<mapper namespace = "dao.CourseDao">
    <select id="findCourseById" resultType = "Course">
        select * from course where id=#{courseId}

    </select>
</mapper>



CourseDaoTest.java



package test;

import model.Course;

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 dao.CourseDao;

public class CourseDaoTest {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		SqlSessionFactory sqlSessionFactory = getSessionFactory();
		SqlSession sqlSession = sqlSessionFactory.openSession();
		CourseDao courseDao = sqlSession.getMapper(CourseDao.class);
		Course course = courseDao.findCourseById(1);
		System.out.println(course);
	}
	
	private static SqlSessionFactory getSessionFactory(){
		SqlSessionFactory sessionFactory = null;
		String resource = "./configuration.xml";
		try {
			sessionFactory = new SqlSessionFactoryBuilder().build(Resources.getResourceAsReader(resource));
		} catch (Exception e) {
			// TODO: handle exception
		}
		
		return sessionFactory;
	}

}




上面的示例,我们针对course, 简单演示了 select的用法, 不过有个问题值得思考: 一个studentnew可以对应多个course, 那么,在mybatis中如何处理这种一对多, 甚至于多对多,一对一的关系呢?

这儿,就不得不提到 resultMap 这个东西, mybatis的resultMap功能可谓十分强大,能够处理复杂的关系映射, 那么resultMap 该怎么配置呢? 别急,这就来了:

resultMap的配置:

<!-- 
        1.type 对应类型,可以是javabean, 也可以是其它
        2.id 必须唯一, 用于标示这个resultMap的唯一性,在使用resultMap的时候,就是通过id指定
     -->
    <resultMap type="" id="">
    
        <!-- id, 唯一性,注意啦,这个id用于标示这个javabean对象的唯一性, 不一定会是数据库的主键(不要把它理解为数据库对应表的主键) 
            property属性对应javabean的属性名,column对应数据库表的列名
            (这样,当javabean的属性与数据库对应表的列名不一致的时候,就能通过指定这个保持正常映射了)
        -->
        <id property="" column=""/>
        
        <!-- result与id相比, 对应普通属性 -->    
        <result property="" column=""/>
        
        <!-- 
            constructor对应javabean中的构造方法
         -->
        <constructor>
            <!-- idArg 对应构造方法中的id参数 -->
            <idArg column=""/>
            <!-- arg 对应构造方法中的普通参数 -->
            <arg column=""/>
        </constructor>
        
        <!-- 
            collection,对应javabean中容器类型, 是实现一对多的关键 
            property 为javabean中容器对应字段名
            column 为体现在数据库中列名
            ofType 就是指定javabean中容器指定的类型
        -->
        <collection property="" column="" ofType=""></collection>
        
        <!-- 
            association 为关联关系,是实现N对一的关键。
            property 为javabean中容器对应字段名
            column 为体现在数据库中列名
            javaType 指定关联的类型
         -->
        <association property="" column="" javaType=""></association>
    </resultMap>



好啦,知道resutMap怎么配置后,咱们立即接着上面的demo来练习一下吧:

------------------------------------------------------------------下面是用resultMap处理一对多关系的映射的示例-------------------------------------------------------------

一个studentnew对应多个course, 典型的一对多,咱们就来看看mybatis怎么配置这种映射吧:

studentnewDao.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">

<mapper namespace = "dao.StudentNewDao">
    
    
    <resultMap type = "StudentNew" id = "StudnetMap">
        
        <id property = "idCard" column = "idcard"/>
        <result property = "id" column = "id"/>
        <result property = "name" column = "name"/>
        <result property = "deleteFlag" column = "deleteflag"/>
        
        <collection property = "courseList" column = "coueseid" ofType = "Course">
            <id property = "id" column = "id"/>
            <result property = "name" column = "name"/>
            <result property = "deleteFlag" column = "deleteFlag"/>
        </collection>
    </resultMap>
    
    <select id="findStudentNewById" resultMap = "StudnetMap">
        SELECT s.*, c.* FROM studentnew s LEFT JOIN course c ON s.courseid=c.id WHERE s.idcard=#{idCard}

    </select>
</mapper>



StudentNewDaoTest.java

package test;

import java.io.IOException;
import java.util.List;

import model.Course;
import model.StudentNew;

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 dao.StudentNewDao;

public class StudentNewDaoTest {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		SqlSessionFactory sessionFactory = getSessionFactory();
		SqlSession session = sessionFactory.openSession();
		StudentNewDao studentNewDao = session.getMapper(StudentNewDao.class);
		StudentNew studentNew = studentNewDao.findStudentNewById("20140101");
		List<Course> courses = studentNew.getCourseList();
		for(Course c:courses){
			System.out.println(c);
		}
		
	}
	private static SqlSessionFactory getSessionFactory(){
		SqlSessionFactory sqlSessionFactory = null;
		String resource = "./configuration.xml";
		try {
			sqlSessionFactory = new SqlSessionFactoryBuilder().build(Resources.getResourceAsReader(resource));
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return sqlSessionFactory;
	}

}



相信通过以上demo, 大家也能够使用mybatis的select 和 resultMap的用法了。上面demo只演示了一对多的映射,其实多对一、多对多也与它类似,所以我就没演示了,有兴趣的可以自己动手再做做。

好啦,本次就写到这儿了。(PS,生病一周了,所以到现在才更新博客)。

另附上demo, 需要的童鞋可以前往下载:

demo 下载地址:http://pan.baidu.com/s/1qWjsDzA

另外值得注意的地方:

studentNewDao如果重载了构造函数,一定要自己写一个空的默认构造函数,否则报错,

详见:http://zhangsha1251.blog.163.com/blog/static/6262405320111037220994/


易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!