上篇《深入淺出Mybatis系列(七)---mapper映射文件配置之insert、update、delete》介紹了insert、update、delete的用法,本篇將介紹select、resultMap的用法。select無疑是我們最常用,也是最復(fù)雜的,mybatis通過resultMap能幫助我們很好地進(jìn)行高級映射。下面就開始看看select 以及 resultMap的用法:
先看select的配置吧:
<select <!-- 1. id (必須配置) id是命名空間中的唯一標(biāo)識符,可被用來代表這條語句。 一個命名空間(namespace) 對應(yīng)一個dao接口, 這個id也應(yīng)該對應(yīng)dao里面的某個方法(相當(dāng)于方法的實(shí)現(xiàn)),因此id 應(yīng)該與方法名一致 --> id="selectPerson" <!-- 2. parameterType (可選配置, 默認(rèn)為mybatis自動選擇處理) 將要傳入語句的參數(shù)的完全限定類名或別名, 如果不配置,mybatis會通過ParameterHandler 根據(jù)參數(shù)類型默認(rèn)選擇合適的typeHandler進(jìn)行處理 parameterType 主要指定參數(shù)類型,可以是int, short, long, string等類型,也可以是復(fù)雜類型(如對象) --> parameterType="int" <!-- 3. resultType (resultType 與 resultMap 二選一配置) resultType用以指定返回類型,指定的類型可以是基本類型,可以是java容器,也可以是javabean --> resultType="hashmap" <!-- 4. resultMap (resultType 與 resultMap 二選一配置) resultMap用于引用我們通過 resultMap標(biāo)簽定義的映射類型,這也是mybatis組件高級復(fù)雜映射的關(guān)鍵 --> resultMap="personResultMap" <!-- 5. flushCache (可選配置) 將其設(shè)置為 true,任何時候只要語句被調(diào)用,都會導(dǎo)致本地緩存和二級緩存都會被清空,默認(rèn)值:false --> flushCache="false" <!-- 6. useCache (可選配置) 將其設(shè)置為 true,將會導(dǎo)致本條語句的結(jié)果被二級緩存,默認(rèn)值:對 select 元素為 true --> useCache="true" <!-- 7. timeout (可選配置) 這個設(shè)置是在拋出異常之前,驅(qū)動程序等待數(shù)據(jù)庫返回請求結(jié)果的秒數(shù)。默認(rèn)值為 unset(依賴驅(qū)動)--> timeout="10000" <!-- 8. fetchSize (可選配置) 這是嘗試影響驅(qū)動程序每次批量返回的結(jié)果行數(shù)和這個設(shè)置值相等。默認(rèn)值為 unset(依賴驅(qū)動)--> fetchSize="256" <!-- 9. statementType (可選配置) STATEMENT,PREPARED 或 CALLABLE 的一個。這會讓 MyBatis 分別使用 Statement,PreparedStatement 或 CallableStatement,默認(rèn)值:PREPARED--> statementType="PREPARED" <!-- 10. resultSetType (可選配置) FORWARD_ONLY,SCROLL_SENSITIVE 或 SCROLL_INSENSITIVE 中的一個,默認(rèn)值為 unset (依賴驅(qū)動)--> resultSetType="FORWARD_ONLY">
配置看起來總是這么多,不過實(shí)際常用的配置也就那么幾個, 根據(jù)自己的需要吧,上面都已注明是否必須配置。
下面還是上個demo及時練練手吧:
------------------------------------------------------------------------下面是針對select 的練手demo---------------------------------------------------------------------------------------
數(shù)據(jù)庫:新增兩張表(t_course, t_student)
t_course:

t_student:

其中,1個student可選擇多個course進(jìn)行學(xué)習(xí)。
我們還是拿上篇文章的demo, 繼續(xù)寫:
增加后,項(xiàng)目目錄如下所示:

Course.java:

package com.dy.entity;public class Course { private int id; private String name; private int deleteFlag; public int getId() { return id; } public void setId(int id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public int getDeleteFlag() { return deleteFlag; } public void setDeleteFlag(int deleteFlag) { this.deleteFlag = deleteFlag; } }View CodeStudent.java:

package com.dy.entity;import java.util.List;public class Student { private int id; private String idCard; private String name; private List<Course> courseList; private int deleteFlag; public Student(int id, String idCard, String name, List<Course> courseList, int deleteFlag) { this.id = id; this.idCard = idCard; this.name = name; this.courseList = courseList; this.deleteFlag = deleteFlag; } public int getId() { return id; } public void setId(int id) { this.id = id; } public String getIdCard() { return idCard; } public void setIdCard(String idCard) { this.idCard = idCard; } public String getName() { return name; } public void setName(String name) { this.name = name; } public List<Course> getCourseList() { return courseList; } public void setCourseList(List<Course> courseList) { this.courseList = courseList; } public int getDeleteFlag() { return deleteFlag; } public void setDeleteFlag(int deleteFlag) { this.deleteFlag = deleteFlag; }}View CodeCourseDao.java:

package com.dy.dao;import com.dy.entity.Course;public interface CourseDao { public Course findCourseById(int courseId); }View CodeStudentDao.java:

package com.dy.dao;import com.dy.entity.Student;public interface StudentDao { public Student findStudentById(String idCard);}View CodecourseDao.xml:
<mapper namespace="com.dy.dao.CourseDao"> <!-- 1.此處直接將resultType 設(shè)置為course, 一看就知道我設(shè)置了別名吧,如果沒有設(shè)置別名,那么resultType = com.dy.entity.Course。 2.可能細(xì)心的你會發(fā)現(xiàn):Course.java中的屬性名與數(shù)據(jù)庫字段名不一致,下面,我就在sql語句中用了as, 使之匹配,當(dāng)然方法不止一種, 在學(xué)習(xí)了resultMap之后,你能看到一種更直觀優(yōu)雅的方式去將javabean中的屬性與數(shù)據(jù)庫字段名保持一致 3.findCourseById 與CourseDao中findCourseById方法對應(yīng), 那么傳入的參數(shù)名稱以及類型也應(yīng)該保持對應(yīng)關(guān)系。 4.可以看到,在sql語句中,通過#{}表達(dá)式可以獲取參數(shù)。 5.下面這條sql語句,實(shí)際上的形式是怎么樣的?還記得之前說過,mybatis默認(rèn)為preparedStatement吧,那么,用我們jdbc代碼來看,它其實(shí)就是: select course_id as id, course_name as name, course_delete_flg as deleteFlag from t_course where course_id=? --> <select id="findCourseById" resultType="course" > select course_id as id, course_name as name, course_delete_flg as deleteFlag from t_course where course_id=#{courseId} </select> </mapper>CourseDaoTest.java:

package com.dy.dao;import java.io.IOException;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.dy.entity.Course;public class CourseDaoTest { @Test public void findCourseById() { SqlSessionFactory sqlSessionFactory = getSessionFactory(); SqlSession sqlSession = sqlSessionFactory.openSession(); CourseDao courseDao = sqlSession.getMapper(CourseDao.class); Course course = courseDao.findCourseById(1); } //Mybatis 通過SqlSessionFactory獲取SqlSession, 然后才能通過SqlSession與數(shù)據(jù)庫進(jìn)行交互 private static SqlSessionFactory getSessionFactory() { SqlSessionFactory sessionFactory = null; String resource = "mybatis-conf.xml"; try { sessionFactory = new SqlSessionFactoryBuilder().build(Resources .getResourceAsReader(resource)); } catch (IOException e) { e.printStackTrace(); } return sessionFactory; } }View Code
上面的示例,我們針對course, 簡單演示了 select的用法, 不過有個問題值得思考: 一個student可以對應(yīng)多個course, 那么,在mybatis中如何處理這種一對多, 甚至于多對多,一對一的關(guān)系呢?
這兒,就不得不提到 resultMap 這個東西, mybatis的resultMap功能可謂十分強(qiáng)大,能夠處理復(fù)雜的關(guān)系映射, 那么resultMap 該怎么配置呢? 別急,這就來了:
resultMap的配置:
<!-- 1.type 對應(yīng)類型,可以是javabean, 也可以是其它 2.id 必須唯一, 用于標(biāo)示這個resultMap的唯一性,在使用resultMap的時候,就是通過id指定 --> <resultMap type="" id=""> <!-- id, 唯一性,注意啦,這個id用于標(biāo)示這個javabean對象的唯一性, 不一定會是數(shù)據(jù)庫的主鍵(不要把它理解為數(shù)據(jù)庫對應(yīng)表的主鍵) property屬性對應(yīng)javabean的屬性名,column對應(yīng)數(shù)據(jù)庫表的列名 (這樣,當(dāng)javabean的屬性與數(shù)據(jù)庫對應(yīng)表的列名不一致的時候,就能通過指定這個保持正常映射了) --> <id property="" column=""/> <!-- result與id相比, 對應(yīng)普通屬性 --> <result property="" column=""/> <!-- constructor對應(yīng)javabean中的構(gòu)造方法 --> <constructor> <!-- idArg 對應(yīng)構(gòu)造方法中的id參數(shù) --> <idArg column=""/> <!-- arg 對應(yīng)構(gòu)造方法中的普通參數(shù) --> <arg column=""/> </constructor> <!-- collection,對應(yīng)javabean中容器類型, 是實(shí)現(xiàn)一對多的關(guān)鍵 property 為javabean中容器對應(yīng)字段名 column 為體現(xiàn)在數(shù)據(jù)庫中列名 ofType 就是指定javabean中容器指定的類型 --> <collection property="" column="" ofType=""></collection> <!-- association 為關(guān)聯(lián)關(guān)系,是實(shí)現(xiàn)N對一的關(guān)鍵。 property 為javabean中容器對應(yīng)字段名 column 為體現(xiàn)在數(shù)據(jù)庫中列名 javaType 指定關(guān)聯(lián)的類型 --> <association property="" column="" javaType=""></association> </resultMap>
好啦,知道resutMap怎么配置后,咱們立即接著上面的demo來練習(xí)一下吧:
------------------------------------------------------------------下面是用resultMap處理一對多關(guān)系的映射的示例-------------------------------------------------------------
一個student對應(yīng)多個course, 典型的一對多,咱們就來看看mybatis怎么配置這種映射吧:
studentDao.xml:

<mapper namespace="com.dy.dao.StudentDao"> <!-- 這兒定義一個resultMap --> <resultMap type="student" id="studentMap"> <!-- 數(shù)據(jù)庫中主鍵是id, 但是我這兒卻是指定idCard為主鍵,為什么? 剛剛講了,id用來表示唯一性, 我們可以認(rèn)為只要idCard一樣,那么他就是同一個學(xué)生。 如果此處用數(shù)據(jù)庫中id, 那么mybatis將會認(rèn)為數(shù)據(jù)庫中每條記錄都是一個student, 這顯然不符合邏輯 --> <id property="idCard" column="stu_id_card"/> <result property="id" column="stu_id"/> <result property="name" column="stu_name"/> <result property="deleteFlag" column="stu_delete_flg"/> <!-- 這兒就是實(shí)現(xiàn)一對多的關(guān)鍵。 在Student中,courseList為List<Course>, 因此,ofType也應(yīng)該與之對應(yīng)(當(dāng)然,我用了別名,不然要蛋疼的寫全名了)。 collection的子標(biāo)簽是在指定Course的映射關(guān)系(由于Course的javabean的屬性名與數(shù)據(jù)庫的列名不一致) --> <collection property="courseList" column="stu_course_id" ofType="Course"> <id property="id" column="course_id"/> <result property="name" column="course_name"/> <result property="deleteFlag" column="course_delete_flg"/> </collection> </resultMap> <!-- 這兒將返回類型設(shè)置成了上面指定的studentMap --> <select id="findStudentById" resultMap="studentMap"> SELECT s.*, c.* FROM t_student s LEFT JOIN t_course c ON s.stu_course_id=c.course_id WHERE s.stu_id_card=#{idCard} </select> </mapper>View CodeStudentDaoTest.java:

package com.dy.dao;import java.io.IOException;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 org.junit.Test;import com.dy.entity.Course;import com.dy.entity.Student;public class StudentDaoTest { @Test public void findCourseById() { SqlSessionFactory sqlSessionFactory = getSessionFactory(); SqlSession sqlSession = sqlSessionFactory.openSession(); StudentDao studentDao = sqlSession.getMapper(StudentDao.class); Student student = studentDao.findStudentById("20140101"); List<Course> courseList = student.getCourseList(); for (Course course: courseList) { System.out.println(course.getId() + " " + course.getName()); } } //Mybatis 通過SqlSessionFactory獲取SqlSession, 然后才能通過SqlSession與數(shù)據(jù)庫進(jìn)行交互 private static SqlSessionFactory getSessionFactory() { SqlSessionFactory sessionFactory = null; String resource = "mybatis-conf.xml"; try { sessionFactory = new SqlSessionFactoryBuilder().build(Resources .getResourceAsReader(resource)); } catch (IOException e) { e.printStackTrace(); } return sessionFactory; } }View Code相信通過以上demo, 大家也能夠使用mybatis的select 和 resultMap的用法了。上面demo只演示了一對多的映射,其實(shí)多對一、多對多也與它類似,所以我就沒演示了,有興趣的可以自己動手再做做。
好啦,本次就寫到這兒了。(PS,生病一周了,所以到現(xiàn)在才更新博客)。
另附上demo, 需要的童鞋可以前往下載:
demo 下載地址:http://pan.baidu.com/s/1qWjsDzA
新聞熱點(diǎn)
疑難解答
圖片精選