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

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

先看select的配置吧: sql


<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及时练练手吧: apache

------------------------------------------------------------------------下面是针对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进行学习。 session

咱们仍是拿上篇文章的demo, 继续写: mybatis

增长后,项目目录以下所示: app


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只演示了一对多的映射,其实多对1、多对多也与它相似,因此我就没演示了,有兴趣的能够本身动手再作作。

好啦,本次就写到这儿了。(PS,生病一周了,因此到如今才更新博客)。

另附上demo, 须要的童鞋能够前往下载:

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

另外值得注意的地方:

studentNewDao若是重载了构造函数,必定要本身写一个空的默认构造函数,不然报错,

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

相关文章
相关标签/搜索