MyBatis教程


http://limingnihao.iteye.com/blog/781671

一、MyBatis簡介與配置MyBatis+Spring+MySql

1.1MyBatis簡介

      MyBatis 是一個可以自定義SQL、存儲過程和高級映射的持久層框架。MyBatis 摒除了大部分的JDBC代碼、手工設置參數和結果集重獲。MyBatis 只使用簡單的XML 和注解來配置和映射基本數據類型、Map 接口和POJO 到數據庫記錄。相對Hibernate和Apache OJB等“一站式”ORM解決方案而言,Mybatis 是一種“半自動化”的ORM實現。
需要使用的Jar包:mybatis-3.0.2.jar(mybatis核心包)。mybatis-spring-1.0.0.jar(與Spring結合包)。

下載地址:
http://ibatis.apache.org/tools/ibator
http://code.google.com/p/mybatis/

 

1.2MyBatis+Spring+MySql簡單配置

1.2.1搭建Spring環境

1,建立maven的web項目;
2,加入Spring框架、配置文件;
3,在pom.xml中加入所需要的jar包(spring框架的、mybatis、mybatis-spring、junit等);
4,更改web.xml和spring的配置文件;
5,添加一個jsp頁面和對應的Controller;
6,測試。

可參照:http://limingnihao.iteye.com/blog/830409使用Eclipse的Maven構建SpringMVC項目


1.2.2建立MySql數據庫

建立一個學生選課管理數據庫。
表:學生表、班級表、教師表、課程表、學生選課表。
邏輯關系:每個學生有一個班級;每個班級對應一個班主任教師;每個教師只能當一個班的班主任;

使用下面的sql進行建數據庫,先建立學生表,插入數據(2條以上)。

更多sql請下載項目源文件,在resource/sql中。

Sql代碼   收藏代碼
  1. /* 建立數據庫 */  
  2. CREATE DATABASE STUDENT_MANAGER;  
  3. USE STUDENT_MANAGER;  
  4.   
  5. /***** 建立student表 *****/  
  6. CREATE TABLE STUDENT_TBL  
  7. (  
  8.    STUDENT_ID         VARCHAR(255) PRIMARY KEY,  
  9.    STUDENT_NAME       VARCHAR(10) NOT NULL,  
  10.    STUDENT_SEX        VARCHAR(10),  
  11.    STUDENT_BIRTHDAY   DATE,  
  12.    CLASS_ID           VARCHAR(255)  
  13. );  
  14.   
  15. /*插入學生數據*/  
  16. INSERT INTO STUDENT_TBL (STUDENT_ID,  
  17.                          STUDENT_NAME,  
  18.                          STUDENT_SEX,  
  19.                          STUDENT_BIRTHDAY,  
  20.                          CLASS_ID)  
  21.   VALUES   (123456,  
  22.             '某某某',  
  23.             '女',  
  24.             '1980-08-01',  
  25.             121546  
  26.             )  

 


創建連接MySql使用的配置文件mysql.properties。

Mysql.properties代碼   收藏代碼
  1. jdbc.driverClassName=com.mysql.jdbc.Driver  
  2. jdbc.url=jdbc:mysql://localhost:3306/student_manager?user=root&password=limingnihao&useUnicode=true&characterEncoding=UTF-8  

 

 

1.2.3搭建MyBatis環境

順序隨便,現在的順序是因為可以盡量的少的修改寫好的文件。


1.2.3.1創建實體類: StudentEntity

Java代碼   收藏代碼
  1. public class StudentEntity implements Serializable {  
  2.   
  3.     private static final long serialVersionUID = 3096154202413606831L;  
  4.     private ClassEntity classEntity;  
  5.     private Date studentBirthday;  
  6.     private String studentID;  
  7.     private String studentName;  
  8.     private String studentSex;  
  9.       
  10.     public ClassEntity getClassEntity() {  
  11.         return classEntity;  
  12.     }  
  13.   
  14.     public Date getStudentBirthday() {  
  15.         return studentBirthday;  
  16.     }  
  17.   
  18.     public String getStudentID() {  
  19.         return studentID;  
  20.     }  
  21.   
  22.     public String getStudentName() {  
  23.         return studentName;  
  24.     }  
  25.   
  26.     public String getStudentSex() {  
  27.         return studentSex;  
  28.     }  
  29.   
  30.     public void setClassEntity(ClassEntity classEntity) {  
  31.         this.classEntity = classEntity;  
  32.     }  
  33.   
  34.     public void setStudentBirthday(Date studentBirthday) {  
  35.         this.studentBirthday = studentBirthday;  
  36.     }  
  37.   
  38.     public void setStudentID(String studentID) {  
  39.         this.studentID = studentID;  
  40.     }  
  41.   
  42.     public void setStudentName(String studentName) {  
  43.         this.studentName = studentName;  
  44.     }  
  45.   
  46.     public void setStudentSex(String studentSex) {  
  47.         this.studentSex = studentSex;  
  48.     }  
  49. }  

 

 

 

1.2.3.2創建數據訪問接口

Student類對應的dao接口:StudentMapper。

Java代碼   收藏代碼
  1. public interface StudentMapper {  
  2.       
  3.     public StudentEntity getStudent(String studentID);  
  4.       
  5.     public StudentEntity getStudentAndClass(String studentID);  
  6.       
  7.     public List<StudentEntity> getStudentAll();  
  8.       
  9.     public void insertStudent(StudentEntity entity);  
  10.       
  11.     public void deleteStudent(StudentEntity entity);  
  12.       
  13.     public void updateStudent(StudentEntity entity);  
  14. }  

 


1.2.3.3創建SQL映射語句文件


Student類的sql語句文件StudentMapper.xml
resultMap標簽:表字段與屬性的映射。
Select標簽:查詢sql。

Xml代碼   收藏代碼
  1. <?xml version="1.0" encoding="UTF-8" ?>  
  2. <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">  
  3. <mapper namespace="com.manager.data.StudentMapper">  
  4.   
  5.     <resultMap type="StudentEntity" id="studentResultMap">  
  6.         <id property="studentID" column="STUDENT_ID"/>  
  7.         <result property="studentName" column="STUDENT_NAME"/>  
  8.         <result property="studentSex" column="STUDENT_SEX"/>  
  9.         <result property="studentBirthday" column="STUDENT_BIRTHDAY"/>  
  10.     </resultMap>  
  11.       
  12.     <!-- 查詢學生,根據id -->  
  13.     <select id="getStudent" parameterType="String" resultType="StudentEntity" resultMap="studentResultMap">  
  14.         <![CDATA[ 
  15.             SELECT * from STUDENT_TBL ST 
  16.                 WHERE ST.STUDENT_ID = #{studentID}  
  17.         ]]>   
  18.     </select>  
  19.       
  20.     <!-- 查詢學生列表 -->  
  21.     <select id="getStudentAll"  resultType="com.manager.data.model.StudentEntity" resultMap="studentResultMap">  
  22.         <![CDATA[ 
  23.             SELECT * from STUDENT_TBL 
  24.         ]]>   
  25.     </select>  
  26.       
  27. </mapper>  

 

 


1.2.3.4創建MyBatis的mapper配置文件

在src/main/resource中創建MyBatis配置文件:mybatis-config.xml。
typeAliases標簽:給類起一個別名。com.manager.data.model.StudentEntity類,可以使用StudentEntity代替。
Mappers標簽:加載MyBatis中實體類的SQL映射語句文件。

 

Xml代碼   收藏代碼
  1. <?xml version="1.0" encoding="UTF-8" ?>  
  2. <!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config 3.0//EN" "http://mybatis.org/dtd/mybatis-3-config.dtd">  
  3. <configuration>  
  4.     <typeAliases>  
  5.         <typeAlias alias="StudentEntity" type="com.manager.data.model.StudentEntity"/>  
  6.     </typeAliases>  
  7.     <mappers>  
  8.         <mapper resource="com/manager/data/maps/StudentMapper.xml" />  
  9.     </mappers>  
  10. </configuration>    

 

 

 


1.2.3.5修改Spring 的配置文件

主要是添加SqlSession的制作工廠類的bean:SqlSessionFactoryBean,(在mybatis.spring包中)。需要指定配置文件位置和dataSource。
和數據訪問接口對應的實現bean。通過MapperFactoryBean創建出來。需要執行接口類全稱和SqlSession工廠bean的引用。

Xml代碼   收藏代碼
  1. <!-- 導入屬性配置文件 -->  
  2. <context:property-placeholder location="classpath:mysql.properties" />  
  3.   
  4. <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">  
  5.     <property name="driverClassName" value="${jdbc.driverClassName}" />  
  6.     <property name="url" value="${jdbc.url}" />  
  7. </bean>  
  8.   
  9. <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">  
  10.     <property name="dataSource" ref="dataSource" />  
  11. </bean>  
  12.   
  13. <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">  
  14.     <property name="configLocation" value="classpath:mybatis-config.xml" />  
  15.     <property name="dataSource" ref="dataSource" />  
  16. </bean>  
  17.   
  18. <!— mapper bean -->  
  19. <bean id="studentMapper" class="org.mybatis.spring.MapperFactoryBean">  
  20.     <property name="mapperInterface" value="com.manager.data.StudentMapper" />  
  21.     <property name="sqlSessionFactory" ref="sqlSessionFactory" />  
  22. </bean>  

 

 

也可以不定義mapper的bean,使用注解:

將StudentMapper加入注解

 

Java代碼   收藏代碼
  1. @Repository  
  2. @Transactional  
  3. public interface StudentMapper {  
  4. }  
 

 

對應的需要在dispatcher-servlet.xml中加入掃描:

 

Xml代碼   收藏代碼
  1. <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">  
  2.     <property name="annotationClass" value="org.springframework.stereotype.Repository"/>  
  3.     <property name="basePackage" value="com.liming.manager"/>  
  4.     <property name="sqlSessionFactory" ref="sqlSessionFactory"/>  
  5. </bean>  
 

 

 

1.2.4測試StudentMapper

使用SpringMVC測試,創建一個TestController,配置tomcat,訪問index.do頁面進行測試:

Java代碼   收藏代碼
  1. @Controller  
  2. public class TestController {  
  3.   
  4.     @Autowired  
  5.     private StudentMapper studentMapper;  
  6.       
  7.     @RequestMapping(value = "index.do")  
  8.     public void indexPage() {     
  9.         StudentEntity entity = studentMapper.getStudent("10000013");  
  10.         System.out.println("name:" + entity.getStudentName());  
  11.     }     
  12. }  

 

 

使用Junit測試:

Java代碼   收藏代碼
  1. 使用Junit測試:  
  2. Java代碼  
  3. @RunWith(value = SpringJUnit4ClassRunner.class)  
  4. @ContextConfiguration(value = "test-servlet.xml")  
  5. public class StudentMapperTest {  
  6.       
  7.     @Autowired  
  8.     private ClassMapper classMapper;  
  9.       
  10.     @Autowired  
  11.     private StudentMapper studentMapper;  
  12.       
  13.     @Transactional  
  14.     public void getStudentTest(){  
  15.         StudentEntity entity = studentMapper.getStudent("10000013");  
  16.         System.out.println("" + entity.getStudentID() + entity.getStudentName());  
  17.           
  18.         List<StudentEntity> studentList = studentMapper.getStudentAll();  
  19.         for( StudentEntity entityTemp : studentList){  
  20.             System.out.println(entityTemp.getStudentName());  
  21.         }  
  22.           
  23.     }  
  24. }  

SQL 映射XML 文件是所有sql語句放置的地方。需要定義一個workspace,一般定義為對應的接口類的路徑。寫好SQL語句映射文件后,需要在MyBAtis配置文件mappers標簽中引用,例如:

 

Xml代碼   收藏代碼
  1. <mappers>  
  2.     <mapper resource="com/liming/manager/data/mappers/UserMapper.xml" />  
  3.     <mapper resource="com/liming/manager/data/mappers/StudentMapper.xml" />  
  4.     <mapper resource="com/liming/manager/data/mappers/ClassMapper.xml" />  
  5.     <mapper resource="com/liming/manager/data/mappers/TeacherMapper.xml" />  
  6. </mappers>  

 

 

當Java接口與XML文件在一個相對路徑下時,可以不在myBatis配置文件的mappers中聲明。

 


SQL 映射XML 文件一些初級的元素:


1. cache – 配置給定模式的緩存
2. cache-ref – 從別的模式中引用一個緩存
3. resultMap – 這是最復雜而卻強大的一個元素了,它描述如何從結果集中加載對象
4. sql – 一個可以被其他語句復用的SQL 塊
5. insert – 映射INSERT 語句
6. update – 映射UPDATE 語句
7. delete – 映射DELEETE 語句
8. select  -  映射SELECT語句

二、SQL語句映射文件

2.1 resultMap

        resultMap 是MyBatis 中最重要最強大的元素了。你可以讓你比使用JDBC 調用結果集省掉90%的代碼,也可以讓你做許多JDBC 不支持的事。現實上,要寫一個等同類似於交互的映射這樣的復雜語句,可能要上千行的代碼。ResultMaps 的目的,就是這樣簡單的語句而不需要多余的結果映射,更多復雜的語句,除了只要一些絕對必須的語句描述關系以外,再也不需要其它的。

resultMap屬性:type為java實體類;id為此resultMap的標識。

 

 resultMap可以設置的映射:


1. constructor – 用來將結果反射給一個實例化好的類的構造器

a) idArg – ID 參數;將結果集標記為ID,以方便全局調用
b) arg –反射到構造器的通常結果


2. id – ID 結果,將結果集標記為ID,以方便全局調用


3. result – 反射到JavaBean 屬性的普通結果


4. association – 復雜類型的結合;多個結果合成的類型

a) nested result mappings – 幾resultMap 自身嵌套關聯,也可以引用到一個其它上


5. collection –復雜類型集合a collection of complex types


6. nested result mappings – resultMap 的集合,也可以引用到一個其它上


7. discriminator – 使用一個結果值以決定使用哪個resultMap

a) case – 基本一些值的結果映射的case 情形

i. nested result mappings –一個case 情形本身就是一個結果映射,因此也可以包括一些相同的元素,也可以引用一個外部resultMap。

 

 

2.1.1 id、result

id、result是最簡單的映射,id為主鍵映射;result其他基本數據庫表字段到實體類屬性的映射。
  最簡單的例子:

 

Xml代碼   收藏代碼
  1. <resultMap type="liming.student.manager.data.model.StudentEntity" id="studentResultMap">  
  2.     <id  property="studentId"        column="STUDENT_ID" javaType="String" jdbcType="VARCHAR"/>  
  3.     <result property="studentName"       column="STUDENT_NAME" javaType="String" jdbcType="VARCHAR"/>  
  4.     <result property="studentSex"        column="STUDENT_SEX"  javaType="int" jdbcType="INTEGER"/>  
  5.     <result property="studentBirthday"   column="STUDENT_BIRTHDAY"  javaType="Date" jdbcType="DATE"/>  
  6.     <result property="studentPhoto"  column="STUDENT_PHOTO" javaType="byte[]" jdbcType="BLOB" typeHandler="org.apache.ibatis.type.BlobTypeHandler" />  
  7. </resultMap>  

 

 

 

id、result語句屬性配置細節:

 

屬性

描述

 

property

需要映射到JavaBean 的屬性名稱。

 

column

數據表的列名或者標簽別名。

 

javaType

一個完整的類名,或者是一個類型別名。如果你匹配的是一個JavaBean,那MyBatis 通常會自行檢測到。然后,如果你是要映射到一個HashMap,那你需要指定javaType 要達到的目的。

 

jdbcType

數據表支持的類型列表。這個屬性只在insert,update 或delete 的時候針對允許空的列有用。JDBC 需要這項,但MyBatis 不需要。如果你是直接針對JDBC 編碼,且有允許空的列,而你要指定這項。

 

typeHandler

使用這個屬性可以覆寫類型處理器。這項值可以是一個完整的類名,也可以是一個類型別名。

 

 

 

支持的JDBC類型
       為了將來的引用,MyBatis 支持下列JDBC 類型,通過JdbcType 枚舉:
BIT,FLOAT,CHAR,TIMESTAMP,OTHER,UNDEFINED,TINYINT,REAL,VARCHAR,BINARY,BLOB,NVARCHAR,SMALLINT,DOUBLE,LONGVARCHAR,VARBINARY,CLOB,NCHAR,INTEGER,NUMERIC,DATE,LONGVARBINARY,BOOLEAN,NCLOB,BIGINT,DECIMAL,TIME,NULL,CURSOR

 

 

2.1.2 constructor


        我們使用id、result時候,需要定義java實體類的屬性映射到數據庫表的字段上。這個時候是使用JavaBean實現的。當然我們也可以使用實體類的構造方法來實現值的映射,這個時候是通過構造方法參數的書寫的順序來進行賦值的。
        使用construcotr功能有限(例如使用collection級聯查詢)。
        上面使用id、result實現的功能就可以改為:

Xml代碼   收藏代碼
  1. <resultMap type="StudentEntity" id="studentResultMap" >  
  2.     <constructor>  
  3.         <idArg javaType="String" column="STUDENT_ID"/>  
  4.         <arg javaType="String" column="STUDENT_NAME"/>  
  5.         <arg javaType="String" column="STUDENT_SEX"/>  
  6.         <arg javaType="Date" column="STUDENT_BIRTHDAY"/>  
  7.     </constructor>  
  8. </resultMap>  

 

        當然,我們需要定義StudentEntity實體類的構造方法:

Java代碼   收藏代碼
  1. public StudentEntity(String studentID, String studentName, String studentSex, Date studentBirthday){  
  2.     this.studentID = studentID;  
  3.     this.studentName = studentName;  
  4.     this.studentSex = studentSex;  
  5.     this.studentBirthday = studentBirthday;  
  6. }  

 

 

 

 

2.1.3 association聯合

聯合元素用來處理“一對一”的關系。需要指定映射的Java實體類的屬性,屬性的javaType(通常MyBatis 自己會識別)。對應的數據庫表的列名稱。如果想覆寫的話返回結果的值,需要指定typeHandler。
不同情況需要告訴MyBatis 如何加載一個聯合。MyBatis 可以用兩種方式加載:

1. select: 執行一個其它映射的SQL 語句返回一個Java實體類型。較靈活;
2. resultsMap: 使用一個嵌套的結果映射來處理通過join查詢結果集,映射成Java實體類型。

 

例如,一個班級對應一個班主任。
 首先定義好班級中的班主任屬性:

Java代碼   收藏代碼
  1. private TeacherEntity teacherEntity;  

 

 

2.1.3.1使用select實現聯合

 例:班級實體類中有班主任的屬性,通過聯合在得到一個班級實體時,同時映射出班主任實體。

 這樣可以直接復用在TeacherMapper.xml文件中定義好的查詢teacher根據其ID的select語句。而且不需要修改寫好的SQL語句,只需要直接修改resultMap即可。


 ClassMapper.xml文件部分內容:

Xml代碼   收藏代碼
  1. <resultMap type="ClassEntity" id="classResultMap">  
  2.     <id property="classID" column="CLASS_ID" />  
  3.     <result property="className" column="CLASS_NAME" />  
  4.     <result property="classYear" column="CLASS_YEAR" />  
  5.     <association property="teacherEntity" column="TEACHER_ID" select="getTeacher"/>  
  6. </resultMap>  
  7.   
  8. <select id="getClassByID" parameterType="String" resultMap="classResultMap">  
  9.     SELECT * FROM CLASS_TBL CT  
  10.     WHERE CT.CLASS_ID = #{classID};  
  11. </select>  

 

 

 TeacherMapper.xml文件部分內容:

Xml代碼   收藏代碼
  1. <resultMap type="TeacherEntity" id="teacherResultMap">  
  2.     <id property="teacherID" column="TEACHER_ID" />  
  3.     <result property="teacherName" column="TEACHER_NAME" />  
  4.     <result property="teacherSex" column="TEACHER_SEX" />  
  5.     <result property="teacherBirthday" column="TEACHER_BIRTHDAY"/>  
  6.     <result property="workDate" column="WORK_DATE"/>  
  7.     <result property="professional" column="PROFESSIONAL"/>  
  8. </resultMap>  
  9.   
  10. <select id="getTeacher" parameterType="String"  resultMap="teacherResultMap">  
  11.     SELECT *  
  12.       FROM TEACHER_TBL TT  
  13.      WHERE TT.TEACHER_ID = #{teacherID}  
  14. </select>  

 

 

 

2.1.3.2使用resultMap實現聯合

 與上面同樣的功能,查詢班級,同時查詢器班主任。需在association中添加resultMap(在teacher的xml文件中定義好的),新寫sql(查詢班級表left join教師表),不需要teacher的select。


 修改ClassMapper.xml文件部分內容:

Xml代碼   收藏代碼
  1. <resultMap type="ClassEntity" id="classResultMap">  
  2.     <id property="classID" column="CLASS_ID" />  
  3.     <result property="className" column="CLASS_NAME" />  
  4.     <result property="classYear" column="CLASS_YEAR" />  
  5.     <association property="teacherEntity" column="TEACHER_ID"  resultMap="teacherResultMap"/>  
  6. </resultMap>  
  7.   
  8. <select id="getClassAndTeacher" parameterType="String" resultMap="classResultMap">  
  9.     SELECT *  
  10.       FROM CLASS_TBL CT LEFT JOIN TEACHER_TBL TT ON CT.TEACHER_ID = TT.TEACHER_ID  
  11.      WHERE CT.CLASS_ID = #{classID};  
  12. </select>  

 

其中的teacherResultMap請見上面TeacherMapper.xml文件部分內容中。

 

 

2.1.4 collection聚集

聚集元素用來處理“一對多”的關系。需要指定映射的Java實體類的屬性,屬性的javaType(一般為ArrayList);列表中對象的類型ofType(Java實體類);對應的數據庫表的列名稱;
不同情況需要告訴MyBatis 如何加載一個聚集。MyBatis 可以用兩種方式加載:

1. select: 執行一個其它映射的SQL 語句返回一個Java實體類型。較靈活;
2. resultsMap: 使用一個嵌套的結果映射來處理通過join查詢結果集,映射成Java實體類型。

 

例如,一個班級有多個學生。
首先定義班級中的學生列表屬性:

Java代碼   收藏代碼
  1. private List<StudentEntity> studentList;  

 

 

2.1.4.1使用select實現聚集

 用法和聯合很類似,區別在於,這是一對多,所以一般映射過來的都是列表。所以這里需要定義javaType為ArrayList,還需要定義列表中對象的類型ofType,以及必須設置的select的語句名稱(需要注意的是,這里的查詢student的select語句條件必須是外鍵classID)。

 

ClassMapper.xml文件部分內容:

Xml代碼   收藏代碼
  1. <resultMap type="ClassEntity" id="classResultMap">  
  2.     <id property="classID" column="CLASS_ID" />  
  3.     <result property="className" column="CLASS_NAME" />  
  4.     <result property="classYear" column="CLASS_YEAR" />  
  5.     <association property="teacherEntity" column="TEACHER_ID"  select="getTeacher"/>  
  6.     <collection property="studentList" column="CLASS_ID" javaType="ArrayList" ofType="StudentEntity" select="getStudentByClassID"/>  
  7. </resultMap>  
  8.   
  9. <select id="getClassByID" parameterType="String" resultMap="classResultMap">  
  10.     SELECT * FROM CLASS_TBL CT  
  11.     WHERE CT.CLASS_ID = #{classID};  
  12. </select>  

 

 

 

StudentMapper.xml文件部分內容:

Xml代碼   收藏代碼
  1. <!-- java屬性,數據庫表字段之間的映射定義 -->  
  2. <resultMap type="StudentEntity" id="studentResultMap">  
  3.     <id property="studentID" column="STUDENT_ID" />  
  4.     <result property="studentName" column="STUDENT_NAME" />  
  5.     <result property="studentSex" column="STUDENT_SEX" />  
  6.     <result property="studentBirthday" column="STUDENT_BIRTHDAY" />  
  7. </resultMap>  
  8.   
  9. <!-- 查詢學生list,根據班級id -->  
  10. <select id="getStudentByClassID" parameterType="String" resultMap="studentResultMap">  
  11.     <include refid="selectStudentAll" />  
  12.     WHERE ST.CLASS_ID = #{classID}  
  13. </select>  

 

 

 


2.1.4.2使用resultMap實現聚集

 使用resultMap,就需要重寫一個sql,left join學生表。

Xml代碼   收藏代碼
  1. <resultMap type="ClassEntity" id="classResultMap">  
  2.     <id property="classID" column="CLASS_ID" />  
  3.     <result property="className" column="CLASS_NAME" />  
  4.     <result property="classYear" column="CLASS_YEAR" />  
  5.     <association property="teacherEntity" column="TEACHER_ID"  resultMap="teacherResultMap"/>  
  6.     <collection property="studentList" column="CLASS_ID" javaType="ArrayList" ofType="StudentEntity" resultMap="studentResultMap"/>  
  7. </resultMap>  
  8.   
  9. <select id="getClassAndTeacherStudent" parameterType="String" resultMap="classResultMap">  
  10.     SELECT *  
  11.       FROM CLASS_TBL CT  
  12.            LEFT JOIN STUDENT_TBL ST  
  13.               ON CT.CLASS_ID = ST.CLASS_ID  
  14.            LEFT JOIN TEACHER_TBL TT  
  15.               ON CT.TEACHER_ID = TT.TEACHER_ID  
  16.       WHERE CT.CLASS_ID = #{classID};  
  17. </select>  

 
其中的teacherResultMap請見上面TeacherMapper.xml文件部分內容中。studentResultMap請見上面StudentMapper.xml文件部分內容中。

 

2.1.5discriminator鑒別器

 

有時一個單獨的數據庫查詢也許返回很多不同(但是希望有些關聯)數據類型的結果集。鑒別器元素就是被設計來處理這個情況的,還有包括類的繼承層次結構。鑒別器非常容易理解,因為它的表現很像Java語言中的switch語句。

定義鑒別器指定了column和javaType屬性。列是MyBatis查找比較值的地方。JavaType是需要被用來保證等價測試的合適類型(盡管字符串在很多情形下都會有用)。

下面這個例子為,當classId為20000001時,才映射classId屬性。

 

 

 

Xml代碼   收藏代碼
  1. <resultMap type="liming.student.manager.data.model.StudentEntity" id="resultMap_studentEntity_discriminator">  
  2.     <id  property="studentId"        column="STUDENT_ID" javaType="String" jdbcType="VARCHAR"/>  
  3.     <result property="studentName"       column="STUDENT_NAME" javaType="String" jdbcType="VARCHAR"/>  
  4.     <result property="studentSex"        column="STUDENT_SEX"  javaType="int" jdbcType="INTEGER"/>  
  5.     <result property="studentBirthday"   column="STUDENT_BIRTHDAY"  javaType="Date" jdbcType="DATE"/>  
  6.     <result property="studentPhoto"  column="STUDENT_PHOTO" javaType="byte[]" jdbcType="BLOB" typeHandler="org.apache.ibatis.type.BlobTypeHandler" />  
  7.     <result property="placeId"           column="PLACE_ID" javaType="String" jdbcType="VARCHAR"/>  
  8.     <discriminator column="CLASS_ID" javaType="String" jdbcType="VARCHAR">  
  9.         <case value="20000001" resultType="liming.student.manager.data.model.StudentEntity" >  
  10.             <result property="classId" column="CLASS_ID" javaType="String" jdbcType="VARCHAR"/>  
  11.         </case>  
  12.     </discriminator>  
  13. </resultMap>  
 

2.2 select

一個select 元素非常簡單。例如:

Xml代碼   收藏代碼
  1. <!-- 查詢學生,根據id -->  
  2. <select id="getStudent" parameterType="String" resultMap="studentResultMap">  
  3.     SELECT ST.STUDENT_ID,  
  4.                ST.STUDENT_NAME,  
  5.                ST.STUDENT_SEX,  
  6.                ST.STUDENT_BIRTHDAY,  
  7.                ST.CLASS_ID  
  8.           FROM STUDENT_TBL ST  
  9.          WHERE ST.STUDENT_ID = #{studentID}  
  10. </select>  

 


這條語句就叫做‘getStudent,有一個String參數,並返回一個StudentEntity類型的對象。
注意參數的標識是:#{studentID}。

 

select 語句屬性配置細節: 

屬性 描述 取值 默認
id 在這個模式下唯一的標識符,可被其它語句引用    
parameterType 傳給此語句的參數的完整類名或別名    
resultType 語句返回值類型的整類名或別名。注意,如果是集合,那么這里填寫的是集合的項的整類名或別名,而不是集合本身的類名。(resultType 與resultMap 不能並用)    
resultMap 引用的外部resultMap 名。結果集映射是MyBatis 中最強大的特性。許多復雜的映射都可以輕松解決。(resultType 與resultMap 不能並用)    
flushCache 如果設為true,則會在每次語句調用的時候就會清空緩存。select 語句默認設為false true|false false
useCache 如果設為true,則語句的結果集將被緩存。select 語句默認設為false true|false false
timeout 設置驅動器在拋出異常前等待回應的最長時間,默認為不設值,由驅動器自己決定
true|false false
timeout  設置驅動器在拋出異常前等待回應的最長時間,默認為不設值,由驅動器自己決定 正整數 未設置
fetchSize 設置一個值后,驅動器會在結果集數目達到此數值后,激發返回,默認為不設值,由驅動器自己決定 正整數 驅動器決定
statementType statement,preparedstatement,callablestatement。
預准備語句、可調用語句
STATEMENT
PREPARED
CALLABLE
PREPARED
resultSetType forward_only,scroll_sensitive,scroll_insensitive
只轉發,滾動敏感,不區分大小寫的滾動
FORWARD_ONLY
SCROLL_SENSITIVE
SCROLL_INSENSITIVE
驅動器決定

 

 

2.3 insert

 一個簡單的insert語句:

Xml代碼   收藏代碼
  1. <!-- 插入學生 -->  
  2. <insert id="insertStudent" parameterType="StudentEntity">  
  3.         INSERT INTO STUDENT_TBL (STUDENT_ID,  
  4.                                           STUDENT_NAME,  
  5.                                           STUDENT_SEX,  
  6.                                           STUDENT_BIRTHDAY,  
  7.                                           CLASS_ID)  
  8.               VALUES   (#{studentID},  
  9.                           #{studentName},  
  10.                           #{studentSex},  
  11.                           #{studentBirthday},  
  12.                           #{classEntity.classID})  
  13. </insert>  

 

 

 

 insert可以使用數據庫支持的自動生成主鍵策略,設置useGeneratedKeys=”true”,然后把keyProperty 設成對應的列,就搞定了。比如說上面的StudentEntity 使用auto-generated 為id 列生成主鍵.
 還可以使用selectKey元素。下面例子,使用mysql數據庫nextval('student')為自定義函數,用來生成一個key。

Xml代碼   收藏代碼
  1. <!-- 插入學生 自動主鍵-->  
  2. <insert id="insertStudentAutoKey" parameterType="StudentEntity">  
  3.     <selectKey keyProperty="studentID" resultType="String" order="BEFORE">  
  4.             select nextval('student')  
  5.     </selectKey>  
  6.         INSERT INTO STUDENT_TBL (STUDENT_ID,  
  7.                                  STUDENT_NAME,  
  8.                                  STUDENT_SEX,  
  9.                                  STUDENT_BIRTHDAY,  
  10.                                  CLASS_ID)  
  11.               VALUES   (#{studentID},  
  12.                         #{studentName},  
  13.                         #{studentSex},  
  14.                         #{studentBirthday},  
  15.                         #{classEntity.classID})      
  16. </insert>  

 

 

insert語句屬性配置細節:

屬性 描述 取值 默認
id 在這個模式下唯一的標識符,可被其它語句引用    
parameterType 傳給此語句的參數的完整類名或別名    
flushCache 如果設為true,則會在每次語句調用的時候就會清空緩存。select 語句默認設為false true|false false
useCache 如果設為true,則語句的結果集將被緩存。select 語句默認設為false true|false false
timeout 設置驅動器在拋出異常前等待回應的最長時間,默認為不設值,由驅動器自己決定
true|false false
timeout  設置驅動器在拋出異常前等待回應的最長時間,默認為不設值,由驅動器自己決定 正整數 未設置
fetchSize 設置一個值后,驅動器會在結果集數目達到此數值后,激發返回,默認為不設值,由驅動器自己決定 正整數 驅動器決定
statementType statement,preparedstatement,callablestatement。
預准備語句、可調用語句
STATEMENT
PREPARED
CALLABLE
PREPARED
useGeneratedKeys

告訴MyBatis 使用JDBC 的getGeneratedKeys 方法來獲取數據庫自己生成的主鍵(MySQL、SQLSERVER 等

關系型數據庫會有自動生成的字段)。默認:false

true|false false
keyProperty

標識一個將要被MyBatis 設置進getGeneratedKeys 的key 所返回的值,或者為insert 語句使用一個selectKey

子元素。

   

 

 

selectKey語句屬性配置細節:

 

屬性 描述 取值
keyProperty selectKey 語句生成結果需要設置的屬性。  
resultType 生成結果類型,MyBatis 允許使用基本的數據類型,包括String 、int類型。  
order 可以設成BEFORE 或者AFTER,如果設為BEFORE,那它會先選擇主鍵,然后設置keyProperty,再執行insert語句;如果設為AFTER,它就先運行insert 語句再運行selectKey 語句,通常是insert 語句中內部調用數據庫(像Oracle)內嵌的序列機制。  BEFORE
AFTER
statementType 像上面的那樣, MyBatis 支持STATEMENT,PREPARED和CALLABLE 的語句形式, 對應Statement ,PreparedStatement 和CallableStatement 響應 STATEMENT
PREPARED
CALLABLE

 

 

2.4 update、delete

一個簡單的update:

Xml代碼   收藏代碼
  1. <!-- 更新學生信息 -->  
  2. <update id="updateStudent" parameterType="StudentEntity">  
  3.         UPDATE STUDENT_TBL  
  4.             SET STUDENT_TBL.STUDENT_NAME = #{studentName},   
  5.                 STUDENT_TBL.STUDENT_SEX = #{studentSex},  
  6.                 STUDENT_TBL.STUDENT_BIRTHDAY = #{studentBirthday},  
  7.                 STUDENT_TBL.CLASS_ID = #{classEntity.classID}  
  8.          WHERE STUDENT_TBL.STUDENT_ID = #{studentID};     
  9. </update>  

 

一個簡單的delete:

Xml代碼   收藏代碼
  1. <!-- 刪除學生 -->  
  2. <delete id="deleteStudent" parameterType="StudentEntity">  
  3.         DELETE FROM STUDENT_TBL WHERE STUDENT_ID = #{studentID}  
  4. </delete>  

 

 update、delete語句屬性配置細節:

 

屬性 描述 取值 默認
id 在這個模式下唯一的標識符,可被其它語句引用    
parameterType 傳給此語句的參數的完整類名或別名    
flushCache 如果設為true,則會在每次語句調用的時候就會清空緩存。select 語句默認設為false true|false false
useCache 如果設為true,則語句的結果集將被緩存。select 語句默認設為false true|false false
timeout 設置驅動器在拋出異常前等待回應的最長時間,默認為不設值,由驅動器自己決定
true|false false
timeout  設置驅動器在拋出異常前等待回應的最長時間,默認為不設值,由驅動器自己決定 正整數 未設置
fetchSize 設置一個值后,驅動器會在結果集數目達到此數值后,激發返回,默認為不設值,由驅動器自己決定 正整數 驅動器決定
statementType statement,preparedstatement,callablestatement。
預准備語句、可調用語句
STATEMENT
PREPARED
CALLABLE
PREPARED

 

2.5 sql

Sql元素用來定義一個可以復用的SQL 語句段,供其它語句調用。比如:

Xml代碼   收藏代碼
  1. <!-- 復用sql語句  查詢student表所有字段 -->  
  2. <sql id="selectStudentAll">  
  3.         SELECT ST.STUDENT_ID,  
  4.                    ST.STUDENT_NAME,  
  5.                    ST.STUDENT_SEX,  
  6.                    ST.STUDENT_BIRTHDAY,  
  7.                    ST.CLASS_ID  
  8.               FROM STUDENT_TBL ST  
  9. </sql>  

 
   這樣,在select的語句中就可以直接引用使用了,將上面select語句改成:

Xml代碼   收藏代碼
  1. <!-- 查詢學生,根據id -->  
  2. <select id="getStudent" parameterType="String" resultMap="studentResultMap">  
  3.     <include refid="selectStudentAll"/>  
  4.             WHERE ST.STUDENT_ID = #{studentID}   
  5. </select>  

 

 2.6parameters

        上面很多地方已經用到了參數,比如查詢、修改、刪除的條件,插入,修改的數據等,MyBatis可以使用的基本數據類型和Java的復雜數據類型。
        基本數據類型,String,int,date等。
        但是使用基本數據類型,只能提供一個參數,所以需要使用Java實體類,或Map類型做參數類型。通過#{}可以直接得到其屬性。

2.6.1基本類型參數

 根據入學時間,檢索學生列表:

Xml代碼   收藏代碼
  1. <!-- 查詢學生list,根據入學時間  -->  
  2. <select id="getStudentListByDate"  parameterType="Date" resultMap="studentResultMap">  
  3.     SELECT *  
  4.       FROM STUDENT_TBL ST LEFT JOIN CLASS_TBL CT ON ST.CLASS_ID = CT.CLASS_ID  
  5.      WHERE CT.CLASS_YEAR = #{classYear};      
  6. </select>  

 

Java代碼   收藏代碼
  1. List<StudentEntity> studentList = studentMapper.getStudentListByClassYear(StringUtil.parse("2007-9-1"));  
  2. for (StudentEntity entityTemp : studentList) {  
  3.     System.out.println(entityTemp.toString());  
  4. }  

 


2.6.2Java實體類型參數

 根據姓名和性別,檢索學生列表。使用實體類做參數:

Xml代碼   收藏代碼
  1. <!-- 查詢學生list,like姓名、=性別,參數entity類型 -->  
  2. <select id="getStudentListWhereEntity" parameterType="StudentEntity" resultMap="studentResultMap">  
  3.     SELECT * from STUDENT_TBL ST  
  4.         WHERE ST.STUDENT_NAME LIKE CONCAT(CONCAT('%', #{studentName}),'%')  
  5.           AND ST.STUDENT_SEX = #{studentSex}  
  6. </select>  

 

Java代碼   收藏代碼
  1. StudentEntity entity = new StudentEntity();  
  2. entity.setStudentName("李");  
  3. entity.setStudentSex("男");  
  4. List<StudentEntity> studentList = studentMapper.getStudentListWhereEntity(entity);  
  5. for (StudentEntity entityTemp : studentList) {  
  6.     System.out.println(entityTemp.toString());  
  7. }  

 


2.6.3Map參數

根據姓名和性別,檢索學生列表。使用Map做參數:

Xml代碼   收藏代碼
  1. <!-- 查詢學生list,=性別,參數map類型 -->  
  2. <select id="getStudentListWhereMap" parameterType="Map" resultMap="studentResultMap">  
  3.     SELECT * from STUDENT_TBL ST  
  4.      WHERE ST.STUDENT_SEX = #{sex}  
  5.           AND ST.STUDENT_SEX = #{sex}  
  6. </select>  

 

Java代碼   收藏代碼
  1. Map<String, String> map = new HashMap<String, String>();  
  2. map.put("sex""女");  
  3. map.put("name""李");  
  4. List<StudentEntity> studentList = studentMapper.getStudentListWhereMap(map);  
  5. for (StudentEntity entityTemp : studentList) {  
  6.     System.out.println(entityTemp.toString());  
  7. }  

 

 

 

 

2.6.4多參數的實現 

 如果想傳入多個參數,則需要在接口的參數上添加@Param注解。給出一個實例:
 接口寫法:

Java代碼   收藏代碼
  1. public List<StudentEntity> getStudentListWhereParam(@Param(value = "name") String name, @Param(value = "sex") String sex, @Param(value = "birthday") Date birthdar, @Param(value = "classEntity") ClassEntity classEntity);  

 

SQL寫法:

Xml代碼   收藏代碼
  1. <!-- 查詢學生list,like姓名、=性別、=生日、=班級,多參數方式 -->  
  2. <select id="getStudentListWhereParam" resultMap="studentResultMap">  
  3.     SELECT * from STUDENT_TBL ST  
  4.     <where>  
  5.         <if test="name!=null and name!='' ">  
  6.             ST.STUDENT_NAME LIKE CONCAT(CONCAT('%', #{name}),'%')  
  7.         </if>  
  8.         <if test="sex!= null and sex!= '' ">  
  9.             AND ST.STUDENT_SEX = #{sex}  
  10.         </if>  
  11.         <if test="birthday!=null">  
  12.             AND ST.STUDENT_BIRTHDAY = #{birthday}  
  13.         </if>  
  14.         <if test="classEntity!=null and classEntity.classID !=null and classEntity.classID!='' ">  
  15.             AND ST.CLASS_ID = #{classEntity.classID}  
  16.         </if>  
  17.     </where>  
  18. </select>  

 

 

進行查詢:

Java代碼   收藏代碼
  1. List<StudentEntity> studentList = studentMapper.getStudentListWhereParam("""",StringUtil.parse("1985-05-28"), classMapper.getClassByID("20000002"));  
  2. for (StudentEntity entityTemp : studentList) {  
  3.     System.out.println(entityTemp.toString());  
  4. }  

 

 

 

2.6.5字符串代入法

        默認的情況下,使用#{}語法會促使MyBatis 生成PreparedStatement 屬性並且使用PreparedStatement 的參數(=?)來安全的設置值。盡量這些是快捷安全,也是經常使用的。但有時候你可能想直接未更改的字符串代入到SQL 語句中。比如說,對於ORDER BY,你可能會這樣使用:ORDER BY ${columnName}但MyBatis 不會修改和規避掉這個字符串。
        注意:這樣地接收和應用一個用戶輸入到未更改的語句中,是非常不安全的。這會讓用戶能植入破壞代碼,所以,要么要求字段不要允許客戶輸入,要么你直接來檢測他的合法性 。

 

 

2.7 cache緩存


        MyBatis 包含一個強在的、可配置、可定制的緩存機制。MyBatis 3 的緩存實現有了許多改進,既強勁也更容易配置。默認的情況,緩存是沒有開啟,除了會話緩存以外,它可以提高性能,且能解決全局依賴。開啟二級緩存,你只需要在SQL 映射文件中加入簡單的一行:<cache/>


這句簡單的語句的作用如下:

1. 所有在映射文件里的select 語句都將被緩存。
2. 所有在映射文件里insert,update 和delete 語句會清空緩存。
3. 緩存使用“最近很少使用”算法來回收
4. 緩存不會被設定的時間所清空。
5. 每個緩存可以存儲1024 個列表或對象的引用(不管查詢出來的結果是什么)。
6. 緩存將作為“讀/寫”緩存,意味着獲取的對象不是共享的且對調用者是安全的。不會有其它的調用
7. 者或線程潛在修改。

 

例如,創建一個FIFO 緩存讓60 秒就清空一次,存儲512 個對象結果或列表引用,並且返回的結果是只讀。因為在不用的線程里的兩個調用者修改它們可能會導致引用沖突。

Xml代碼   收藏代碼
  1. <cache eviction="FIFO" flushInterval="60000" size="512" readOnly="true">  
  2. </cache>  

 


    還可以在不同的命名空間里共享同一個緩存配置或者實例。在這種情況下,你就可以使用cache-ref 來引用另外一個緩存。

Xml代碼   收藏代碼
  1. <cache-ref namespace="com.liming.manager.data.StudentMapper"/>  

 


Cache 語句屬性配置細節:

屬性 說明 取值 默認值
eviction 緩存策略:
LRU - 最近最少使用法:移出最近較長周期內都沒有被使用的對象。
FIFI- 先進先出:移出隊列里較早的對象
SOFT - 軟引用:基於軟引用規則,使用垃圾回收機制來移出對象
WEAK - 弱引用:基於弱引用規則,使用垃圾回收機制來強制性地移出對象
LRU
FIFI
SOFT
WEAK
LRU
flushInterval 代表一個合理的毫秒總計時間。默認是不設置,因此使用無間隔清空即只能調用語句來清空。 正整數

不設置

size 緩存的對象的大小 正整數 1024
readOnly

只讀緩存將對所有調用者返回同一個實例。因此都不能被修改,這可以極大的提高性能。可寫的緩存將通過序列

化來返回一個緩存對象的拷貝。這會比較慢,但是比較安全。所以默認值是false。

true|false false

 

三、動態SQL語句

       有些時候,sql語句where條件中,需要一些安全判斷,例如按某一條件查詢時如果傳入的參數是空,此時查詢出的結果很可能是空的,也許我們需要參數為空時,是查出全部的信息。使用Oracle的序列、mysql的函數生成Id。這時我們可以使用動態sql。

       下文均采用mysql語法和函數(例如字符串鏈接函數CONCAT)。

 3.1 selectKey 標簽

       在insert語句中,在Oracle經常使用序列、在MySQL中使用函數來自動生成插入表的主鍵,而且需要方法能返回這個生成主鍵。使用myBatis的selectKey標簽可以實現這個效果。

       下面例子,使用mysql數據庫自定義函數nextval('student'),用來生成一個key,並把他設置到傳入的實體類中的studentId屬性上。所以在執行完此方法后,邊可以通過這個實體類獲取生成的key。

Xml代碼   收藏代碼
  1. <!-- 插入學生 自動主鍵-->  
  2. <insert id="createStudentAutoKey" parameterType="liming.student.manager.data.model.StudentEntity" keyProperty="studentId">  
  3.     <selectKey keyProperty="studentId" resultType="String" order="BEFORE">  
  4.         select nextval('student')  
  5.     </selectKey>  
  6.     INSERT INTO STUDENT_TBL(STUDENT_ID,  
  7.                             STUDENT_NAME,  
  8.                             STUDENT_SEX,  
  9.                             STUDENT_BIRTHDAY,  
  10.                             STUDENT_PHOTO,  
  11.                             CLASS_ID,  
  12.                             PLACE_ID)  
  13.     VALUES (#{studentId},  
  14.             #{studentName},  
  15.             #{studentSex},  
  16.             #{studentBirthday},  
  17.             #{studentPhoto, javaType=byte[], jdbcType=BLOBtypeHandler=org.apache.ibatis.type.BlobTypeHandler},  
  18.             #{classId},  
  19.             #{placeId})  
  20. </insert>  
 

 

 

調用接口方法,和獲取自動生成key

Java代碼   收藏代碼
  1. StudentEntity entity = new StudentEntity();  
  2. entity.setStudentName("黎明你好");  
  3. entity.setStudentSex(1);  
  4. entity.setStudentBirthday(DateUtil.parse("1985-05-28"));  
  5. entity.setClassId("20000001");  
  6. entity.setPlaceId("70000001");  
  7. this.dynamicSqlMapper.createStudentAutoKey(entity);  
  8. System.out.println("新增學生ID: " + entity.getStudentId());  

 

 

selectKey語句屬性配置細節:

 

屬性 描述 取值
keyProperty selectKey 語句生成結果需要設置的屬性。
resultType 生成結果類型,MyBatis 允許使用基本的數據類型,包括String 、int類型。
order

1:BEFORE,會先選擇主鍵,然后設置keyProperty,再執行insert語句;

2:AFTER,就先運行insert 語句再運行selectKey 語句。

BEFORE

AFTER
statementType MyBatis 支持STATEMENT,PREPARED和CALLABLE 的語句形式, 對應Statement ,PreparedStatement 和CallableStatement 響應

STATEMENT

PREPARED

CALLABLE

 

3.2 if標簽

 

 if標簽可用在許多類型的sql語句中,我們以查詢為例。首先看一個很普通的查詢:

Xml代碼   收藏代碼
  1. <!-- 查詢學生list,like姓名 -->  
  2. <select id="getStudentListLikeName" parameterType="StudentEntity" resultMap="studentResultMap">  
  3.     SELECT * from STUDENT_TBL ST   
  4. WHERE ST.STUDENT_NAME LIKE CONCAT(CONCAT('%', #{studentName}),'%')  
  5. </select>  

 

 

但是此時如果studentName或studentSex為null,此語句很可能報錯或查詢結果為空。此時我們使用if動態sql語句先進行判斷,如果值為null或等於空字符串,我們就不進行此條件的判斷,增加靈活性。

參數為實體類StudentEntity。將實體類中所有的屬性均進行判斷,如果不為空則執行判斷條件。

Xml代碼   收藏代碼
  1. <!-- 2 if(判斷參數) - 將實體類不為空的屬性作為where條件 -->  
  2. <select id="getStudentList_if" resultMap="resultMap_studentEntity" parameterType="liming.student.manager.data.model.StudentEntity">  
  3.     SELECT ST.STUDENT_ID,  
  4.            ST.STUDENT_NAME,  
  5.            ST.STUDENT_SEX,  
  6.            ST.STUDENT_BIRTHDAY,  
  7.            ST.STUDENT_PHOTO,  
  8.            ST.CLASS_ID,  
  9.            ST.PLACE_ID  
  10.       FROM STUDENT_TBL ST   
  11.      WHERE  
  12.     <if test="studentName !=null ">  
  13.         ST.STUDENT_NAME LIKE CONCAT(CONCAT('%', #{studentName, jdbcType=VARCHAR}),'%')  
  14.     </if>  
  15.     <if test="studentSex != null and studentSex != '' ">  
  16.         AND ST.STUDENT_SEX = #{studentSex, jdbcType=INTEGER}  
  17.     </if>  
  18.     <if test="studentBirthday != null ">  
  19.         AND ST.STUDENT_BIRTHDAY = #{studentBirthday, jdbcType=DATE}  
  20.     </if>  
  21.     <if test="classId != null and classId!= '' ">  
  22.         AND ST.CLASS_ID = #{classId, jdbcType=VARCHAR}  
  23.     </if>  
  24.     <if test="classEntity != null and classEntity.classId !=null and classEntity.classId !=' ' ">  
  25.         AND ST.CLASS_ID = #{classEntity.classId, jdbcType=VARCHAR}  
  26.     </if>  
  27.     <if test="placeId != null and placeId != '' ">  
  28.         AND ST.PLACE_ID = #{placeId, jdbcType=VARCHAR}  
  29.     </if>  
  30.     <if test="placeEntity != null and placeEntity.placeId != null and placeEntity.placeId != '' ">  
  31.         AND ST.PLACE_ID = #{placeEntity.placeId, jdbcType=VARCHAR}  
  32.     </if>  
  33.     <if test="studentId != null and studentId != '' ">  
  34.         AND ST.STUDENT_ID = #{studentId, jdbcType=VARCHAR}  
  35.     </if>   
  36. </select>  
 

 

 

使用時比較靈活, new一個這樣的實體類,我們需要限制那個條件,只需要附上相應的值就會where這個條件,相反不去賦值就可以不在where中判斷。

Java代碼   收藏代碼
  1. public void select_test_2_1() {  
  2.     StudentEntity entity = new StudentEntity();  
  3.     entity.setStudentName("");  
  4.     entity.setStudentSex(1);  
  5.     entity.setStudentBirthday(DateUtil.parse("1985-05-28"));  
  6.     entity.setClassId("20000001");  
  7.     //entity.setPlaceId("70000001");  
  8.     List<StudentEntity> list = this.dynamicSqlMapper.getStudentList_if(entity);  
  9.     for (StudentEntity e : list) {  
  10.         System.out.println(e.toString());  
  11.     }  
  12. }  
 

 

3.3 if + where 的條件判斷

       當where中的條件使用的if標簽較多時,這樣的組合可能會導致錯誤。我們以在3.1中的查詢語句為例子,當java代碼按如下方法調用時:

Java代碼   收藏代碼
  1. @Test  
  2. public void select_test_2_1() {  
  3.     StudentEntity entity = new StudentEntity();  
  4.     entity.setStudentName(null);  
  5.     entity.setStudentSex(1);  
  6.     List<StudentEntity> list = this.dynamicSqlMapper.getStudentList_if(entity);  
  7.     for (StudentEntity e : list) {  
  8.         System.out.println(e.toString());  
  9.     }  
  10. }  

 

 

如果上面例子,參數studentName為null,將不會進行STUDENT_NAME列的判斷,則會直接導“WHERE AND”關鍵字多余的錯誤SQL。

 

這時我們可以使用where動態語句來解決。這個“where”標簽會知道如果它包含的標簽中有返回值的話,它就插入一個‘where’。此外,如果標簽返回的內容是以AND 或OR 開頭的,則它會剔除掉。

上面例子修改為:

Xml代碼   收藏代碼
  1. <!-- 3 select - where/if(判斷參數) - 將實體類不為空的屬性作為where條件 -->  
  2. <select id="getStudentList_whereIf" resultMap="resultMap_studentEntity" parameterType="liming.student.manager.data.model.StudentEntity">  
  3.     SELECT ST.STUDENT_ID,  
  4.            ST.STUDENT_NAME,  
  5.            ST.STUDENT_SEX,  
  6.            ST.STUDENT_BIRTHDAY,  
  7.            ST.STUDENT_PHOTO,  
  8.            ST.CLASS_ID,  
  9.            ST.PLACE_ID  
  10.       FROM STUDENT_TBL ST   
  11.     <where>  
  12.         <if test="studentName !=null ">  
  13.             ST.STUDENT_NAME LIKE CONCAT(CONCAT('%', #{studentName, jdbcType=VARCHAR}),'%')  
  14.         </if>  
  15.         <if test="studentSex != null and studentSex != '' ">  
  16.             AND ST.STUDENT_SEX = #{studentSex, jdbcType=INTEGER}  
  17.         </if>  
  18.         <if test="studentBirthday != null ">  
  19.             AND ST.STUDENT_BIRTHDAY = #{studentBirthday, jdbcType=DATE}  
  20.         </if>  
  21.         <if test="classId != null and classId!= '' ">  
  22.             AND ST.CLASS_ID = #{classId, jdbcType=VARCHAR}  
  23.         </if>  
  24.         <if test="classEntity != null and classEntity.classId !=null and classEntity.classId !=' ' ">  
  25.             AND ST.CLASS_ID = #{classEntity.classId, jdbcType=VARCHAR}  
  26.         </if>  
  27.         <if test="placeId != null and placeId != '' ">  
  28.             AND ST.PLACE_ID = #{placeId, jdbcType=VARCHAR}  
  29.         </if>  
  30.         <if test="placeEntity != null and placeEntity.placeId != null and placeEntity.placeId != '' ">  
  31.             AND ST.PLACE_ID = #{placeEntity.placeId, jdbcType=VARCHAR}  
  32.         </if>  
  33.         <if test="studentId != null and studentId != '' ">  
  34.             AND ST.STUDENT_ID = #{studentId, jdbcType=VARCHAR}  
  35.         </if>  
  36.     </where>    
  37. </select>  
 

 

 

3.4 if + set 的更新語句

當update語句中沒有使用if標簽時,如果有一個參數為null,都會導致錯誤。

當在update語句中使用if標簽時,如果前面的if沒有執行,則或導致逗號多余錯誤。使用set標簽可以將動態的配置SET 關鍵字,和剔除追加到條件末尾的任何不相關的逗號。

 

       使用if+set標簽修改后,如果某項為null則不進行更新,而是保持數據庫原值。如下示例:

Xml代碼   收藏代碼
  1. <!-- 4 if/set(判斷參數) - 將實體類不為空的屬性更新 -->  
  2. <update id="updateStudent_if_set" parameterType="liming.student.manager.data.model.StudentEntity">  
  3.     UPDATE STUDENT_TBL  
  4.     <set>  
  5.         <if test="studentName != null and studentName != '' ">  
  6.             STUDENT_TBL.STUDENT_NAME = #{studentName},  
  7.         </if>  
  8.         <if test="studentSex != null and studentSex != '' ">  
  9.             STUDENT_TBL.STUDENT_SEX = #{studentSex},  
  10.         </if>  
  11.         <if test="studentBirthday != null ">  
  12.             STUDENT_TBL.STUDENT_BIRTHDAY = #{studentBirthday},  
  13.         </if>  
  14.         <if test="studentPhoto != null ">  
  15.             STUDENT_TBL.STUDENT_PHOTO = #{studentPhoto, javaType=byte[], jdbcType=BLOBtypeHandler=org.apache.ibatis.type.BlobTypeHandler},  
  16.         </if>  
  17.         <if test="classId != '' ">  
  18.             STUDENT_TBL.CLASS_ID = #{classId}  
  19.         </if>  
  20.         <if test="placeId != '' ">  
  21.             STUDENT_TBL.PLACE_ID = #{placeId}  
  22.         </if>  
  23.     </set>  
  24.     WHERE STUDENT_TBL.STUDENT_ID = #{studentId};      
  25. </update>  

 

 

 

3.5 if + trim代替where/set標簽

       trim是更靈活的去處多余關鍵字的標簽,他可以實踐where和set的效果。

 

3.5.1trim代替where

 

Xml代碼   收藏代碼
  1. <!-- 5.1 if/trim代替where(判斷參數) - 將實體類不為空的屬性作為where條件 -->  
  2. <select id="getStudentList_if_trim" resultMap="resultMap_studentEntity">  
  3.     SELECT ST.STUDENT_ID,  
  4.            ST.STUDENT_NAME,  
  5.            ST.STUDENT_SEX,  
  6.            ST.STUDENT_BIRTHDAY,  
  7.            ST.STUDENT_PHOTO,  
  8.            ST.CLASS_ID,  
  9.            ST.PLACE_ID  
  10.       FROM STUDENT_TBL ST   
  11.     <trim prefix="WHERE" prefixOverrides="AND|OR">  
  12.         <if test="studentName !=null ">  
  13.             ST.STUDENT_NAME LIKE CONCAT(CONCAT('%', #{studentName, jdbcType=VARCHAR}),'%')  
  14.         </if>  
  15.         <if test="studentSex != null and studentSex != '' ">  
  16.             AND ST.STUDENT_SEX = #{studentSex, jdbcType=INTEGER}  
  17.         </if>  
  18.         <if test="studentBirthday != null ">  
  19.             AND ST.STUDENT_BIRTHDAY = #{studentBirthday, jdbcType=DATE}  
  20.         </if>  
  21.         <if test="classId != null and classId!= '' ">  
  22.             AND ST.CLASS_ID = #{classId, jdbcType=VARCHAR}  
  23.         </if>  
  24.         <if test="classEntity != null and classEntity.classId !=null and classEntity.classId !=' ' ">  
  25.             AND ST.CLASS_ID = #{classEntity.classId, jdbcType=VARCHAR}  
  26.         </if>  
  27.         <if test="placeId != null and placeId != '' ">  
  28.             AND ST.PLACE_ID = #{placeId, jdbcType=VARCHAR}  
  29.         </if>  
  30.         <if test="placeEntity != null and placeEntity.placeId != null and placeEntity.placeId != '' ">  
  31.             AND ST.PLACE_ID = #{placeEntity.placeId, jdbcType=VARCHAR}  
  32.         </if>  
  33.         <if test="studentId != null and studentId != '' ">  
  34.             AND ST.STUDENT_ID = #{studentId, jdbcType=VARCHAR}  
  35.         </if>  
  36.     </trim>     
  37. </select>  
 

 

3.5.2 trim代替set

 

Xml代碼   收藏代碼
  1. <!-- 5.2 if/trim代替set(判斷參數) - 將實體類不為空的屬性更新 -->  
  2. <update id="updateStudent_if_trim" parameterType="liming.student.manager.data.model.StudentEntity">  
  3.     UPDATE STUDENT_TBL  
  4.     <trim prefix="SET" suffixOverrides=",">  
  5.         <if test="studentName != null and studentName != '' ">  
  6.             STUDENT_TBL.STUDENT_NAME = #{studentName},  
  7.         </if>  
  8.         <if test="studentSex != null and studentSex != '' ">  
  9.             STUDENT_TBL.STUDENT_SEX = #{studentSex},  
  10.         </if>  
  11.         <if test="studentBirthday != null ">  
  12.             STUDENT_TBL.STUDENT_BIRTHDAY = #{studentBirthday},  
  13.         </if>  
  14.         <if test="studentPhoto != null ">  
  15.             STUDENT_TBL.STUDENT_PHOTO = #{studentPhoto, javaType=byte[], jdbcType=BLOBtypeHandler=org.apache.ibatis.type.BlobTypeHandler},  
  16.         </if>  
  17.         <if test="classId != '' ">  
  18.             STUDENT_TBL.CLASS_ID = #{classId},  
  19.         </if>  
  20.         <if test="placeId != '' ">  
  21.             STUDENT_TBL.PLACE_ID = #{placeId}  
  22.         </if>  
  23.     </trim>  
  24.     WHERE STUDENT_TBL.STUDENT_ID = #{studentId}  
  25. </update>  
 

 

 

3.6 choose (when, otherwise)

 

    有時候我們並不想應用所有的條件,而只是想從多個選項中選擇一個。而使用if標簽時,只要test中的表達式為true,就會執行if標簽中的條件。MyBatis提供了choose 元素。if標簽是與(and)的關系,而choose比傲天是或(or)的關系。

    choose標簽是按順序判斷其內部when標簽中的test條件出否成立,如果有一個成立,則choose結束。當choose中所有when的條件都不滿則時,則執行otherwise中的sql。類似於Java 的switch 語句,choose為switch,when為case,otherwise則為default。

    例如下面例子,同樣把所有可以限制的條件都寫上,方面使用。choose會從上到下選擇一個when標簽的test為true的sql執行。安全考慮,我們使用where將choose包起來,放置關鍵字多於錯誤。

Xml代碼   收藏代碼
  1. <!-- 6 choose(判斷參數) - 按順序將實體類第一個不為空的屬性作為where條件 -->  
  2. <select id="getStudentList_choose" resultMap="resultMap_studentEntity" parameterType="liming.student.manager.data.model.StudentEntity">  
  3.     SELECT ST.STUDENT_ID,  
  4.            ST.STUDENT_NAME,  
  5.            ST.STUDENT_SEX,  
  6.            ST.STUDENT_BIRTHDAY,  
  7.            ST.STUDENT_PHOTO,  
  8.            ST.CLASS_ID,  
  9.            ST.PLACE_ID  
  10.       FROM STUDENT_TBL ST   
  11.     <where>  
  12.         <choose>  
  13.             <when test="studentName !=null ">  
  14.                 ST.STUDENT_NAME LIKE CONCAT(CONCAT('%', #{studentName, jdbcType=VARCHAR}),'%')  
  15.             </when >  
  16.             <when test="studentSex != null and studentSex != '' ">  
  17.                 AND ST.STUDENT_SEX = #{studentSex, jdbcType=INTEGER}  
  18.             </when >  
  19.             <when test="studentBirthday != null ">  
  20.                 AND ST.STUDENT_BIRTHDAY = #{studentBirthday, jdbcType=DATE}  
  21.             </when >  
  22.             <when test="classId != null and classId!= '' ">  
  23.                 AND ST.CLASS_ID = #{classId, jdbcType=VARCHAR}  
  24.             </when >  
  25.             <when test="classEntity != null and classEntity.classId !=null and classEntity.classId !=' ' ">  
  26.                 AND ST.CLASS_ID = #{classEntity.classId, jdbcType=VARCHAR}  
  27.             </when >  
  28.             <when test="placeId != null and placeId != '' ">  
  29.                 AND ST.PLACE_ID = #{placeId, jdbcType=VARCHAR}  
  30.             </when >  
  31.             <when test="placeEntity != null and placeEntity.placeId != null and placeEntity.placeId != '' ">  
  32.                 AND ST.PLACE_ID = #{placeEntity.placeId, jdbcType=VARCHAR}  
  33.             </when >  
  34.             <when test="studentId != null and studentId != '' ">  
  35.                 AND ST.STUDENT_ID = #{studentId, jdbcType=VARCHAR}  
  36.             </when >  
  37.             <otherwise>  
  38.             </otherwise>  
  39.         </choose>  
  40.     </where>    
  41. </select>  

 

 

 

 

3.7 foreach

對於動態SQL 非常必須的,主是要迭代一個集合,通常是用於IN 條件。List 實例將使用“list”做為鍵,數組實例以“array” 做為鍵。

foreach元素是非常強大的,它允許你指定一個集合,聲明集合項和索引變量,它們可以用在元素體內。它也允許你指定開放和關閉的字符串,在迭代之間放置分隔符。這個元素是很智能的,它不會偶然地附加多余的分隔符。

注意:你可以傳遞一個List實例或者數組作為參數對象傳給MyBatis。當你這么做的時候,MyBatis會自動將它包裝在一個Map中,用名稱在作為鍵。List實例將會以“list”作為鍵,而數組實例將會以“array”作為鍵。

這個部分是對關於XML配置文件和XML映射文件的而討論的。下一部分將詳細討論Java API,所以你可以得到你已經創建的最有效的映射。

 

 

3.7.1參數為array示例的寫法

 

接口的方法聲明:

Java代碼   收藏代碼
  1. public List<StudentEntity> getStudentListByClassIds_foreach_array(String[] classIds);  

 

動態SQL語句:

Xml代碼   收藏代碼
  1. <!— 7.1 foreach(循環array參數) - 作為where中in的條件 -->  
  2. <select id="getStudentListByClassIds_foreach_array" resultMap="resultMap_studentEntity">  
  3.     SELECT ST.STUDENT_ID,  
  4.            ST.STUDENT_NAME,  
  5.            ST.STUDENT_SEX,  
  6.            ST.STUDENT_BIRTHDAY,  
  7.            ST.STUDENT_PHOTO,  
  8.            ST.CLASS_ID,  
  9.            ST.PLACE_ID  
  10.       FROM STUDENT_TBL ST  
  11.       WHERE ST.CLASS_ID IN   
  12.      <foreach collection="array" item="classIds"  open="(" separator="," close=")">  
  13.         #{classIds}  
  14.      </foreach>  
  15. </select>  

 

測試代碼,查詢學生中,在20000001、20000002這兩個班級的學生:

Java代碼   收藏代碼
  1. @Test  
  2. public void test7_foreach() {  
  3.     String[] classIds = { "20000001""20000002" };  
  4.     List<StudentEntity> list = this.dynamicSqlMapper.getStudentListByClassIds_foreach_array(classIds);  
  5.     for (StudentEntity e : list) {  
  6.         System.out.println(e.toString());  
  7.     }  
  8. <p>}<span style="font-size: 14px; font-weight: bold; white-space: normal;">  </span></p>  


3.7.2參數為list示例的寫法

接口的方法聲明:

Java代碼   收藏代碼
  1. public List<StudentEntity> getStudentListByClassIds_foreach_list(List<String> classIdList);  

 

動態SQL語句:

Xml代碼   收藏代碼
  1. <!-- 7.2 foreach(循環List<String>參數) - 作為where中in的條件 -->  
  2. <select id="getStudentListByClassIds_foreach_list" resultMap="resultMap_studentEntity">  
  3.     SELECT ST.STUDENT_ID,  
  4.            ST.STUDENT_NAME,  
  5.            ST.STUDENT_SEX,  
  6.            ST.STUDENT_BIRTHDAY,  
  7.            ST.STUDENT_PHOTO,  
  8.            ST.CLASS_ID,  
  9.            ST.PLACE_ID  
  10.       FROM STUDENT_TBL ST  
  11.       WHERE ST.CLASS_ID IN   
  12.      <foreach collection="list" item="classIdList"  open="(" separator="," close=")">  
  13.         #{classIdList}  
  14.      </foreach>  
  15. </select>  
  

測試代碼,查詢學生中,在20000001、20000002這兩個班級的學生:

Java代碼   收藏代碼
  1. @Test  
  2. public void test7_2_foreach() {  
  3.     ArrayList<String> classIdList = new ArrayList<String>();  
  4.     classIdList.add("20000001");  
  5.     classIdList.add("20000002");  
  6.     List<StudentEntity> list = this.dynamicSqlMapper.getStudentListByClassIds_foreach_list(classIdList);  
  7.     for (StudentEntity e : list) {  
  8.         System.out.println(e.toString());  
  9.     }  
  10. }  

 

四、MyBatis主配置文件

在定義sqlSessionFactory時需要指定MyBatis主配置文件:

 

Xml代碼   收藏代碼
  1. <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">  
  2.     <property name="configLocation" value="classpath:mybatis-config.xml" />  
  3.     <property name="dataSource" ref="dataSource" />  
  4. </bean>  

 

 

 

MyBatis配置文件中大標簽configuration下子標簽包括:

configuration

|--- properties

|--- settings

|--- typeAliases

|--- typeHandlers

|--- objectFactory

|--- plugins

|--- environments

|--- |--- environment

|--- |--- |--- transactionManager

|--- |--- |__ dataSource

|__ mappers

 

 

 

4.1 properties屬性

 

 

    properties和java的.properties的配置文件有關。配置properties的resource指定.properties的路徑,然后再在properties標簽下配置property的name和value,則可以替換.properties文件中相應屬性值。

 

 

 

Xml代碼   收藏代碼
  1.     <!-- 屬性替換 -->  
  2. <properties resource="mysql.properties">  
  3.     <property name="jdbc.driverClassName" value="com.mysql.jdbc.Driver"/>  
  4.     <property name="jdbc.url" value="jdbc:mysql://localhost:3306/student_manager"/>  
  5.     <property name="username" value="root"/>  
  6.     <property name="password" value="limingnihao"/>  
  7. </properties>  
 

 

4.2 settings設置

 

    這是MyBatis 修改操作運行過程細節的重要的步驟。下方這個表格描述了這些設置項、含義和默認值。

 

 

設置項

描述

允許值

默認值

cacheEnabled

對在此配置文件下的所有cache 進行全局性開/關設置。

true | false

true

lazyLoadingEnabled

全局性設置懶加載。如果設為‘false’,則所有相關聯的都會被初始化加載。

true | false

true

aggressiveLazyLoading

當設置為‘true’的時候,懶加載的對象可能被任何懶屬性全部加載。否則,每個屬性都按需加載。

true | false

true

multipleResultSetsEnabled

允許和不允許單條語句返回多個數據集(取決於驅動需求)

true | false

true

useColumnLabel

使用列標簽代替列名稱。不同的驅動器有不同的作法。參考一下驅動器文檔,或者用這兩個不同的選項進行測試一下。

true | false

true

useGeneratedKeys

允許JDBC 生成主鍵。需要驅動器支持。如果設為了true,這個設置將強制使用被生成的主鍵,有一些驅動器不兼容不過仍然可以執行。

true | false

false

autoMappingBehavior

指定MyBatis 是否並且如何來自動映射數據表字段與對象的屬性。PARTIAL將只自動映射簡單的,沒有嵌套的結果。FULL 將自動映射所有復雜的結果。

NONE,

PARTIAL,

FULL

PARTIAL

defaultExecutorType

配置和設定執行器,SIMPLE 執行器執行其它語句。REUSE 執行器可能重復使用prepared statements 語句,BATCH執行器可以重復執行語句和批量更新。

SIMPLE

REUSE

BATCH

SIMPLE

defaultStatementTimeout

設置一個時限,以決定讓驅動器等待數據庫回應的多長時間為超時

正整數

Not Set

(null)

 

 

例如:

 

 

Xml代碼   收藏代碼
  1. <settings>  
  2.     <setting name="cacheEnabled" value="true" />  
  3.     <setting name="lazyLoadingEnabled" value="true" />  
  4.     <setting name="multipleResultSetsEnabled" value="true" />  
  5.     <setting name="useColumnLabel" value="true" />  
  6.     <setting name="useGeneratedKeys" value="false" />  
  7.     <setting name="enhancementEnabled" value="false" />  
  8.     <setting name="defaultExecutorType" value="SIMPLE" />  
  9. </settings>  
 

 

 

4.3 typeAliases類型別名

 

 

類型別名是Java 類型的簡稱。

它僅僅只是關聯到XML 配置,簡寫冗長的JAVA 類名。例如:

 

 

 

Xml代碼   收藏代碼
  1. <typeAliases>  
  2.     <typeAlias alias="UserEntity" type="com.manager.data.model.UserEntity" />  
  3.     <typeAlias alias="StudentEntity" type="com.manager.data.model.StudentEntity" />  
  4.     <typeAlias alias="ClassEntity" type="com.manager.data.model.ClassEntity" />  
  5. </typeAliases>  
 

 

 

    使用這個配置,“StudentEntity”就能在任何地方代替“com.manager.data.model.StudentEntity”被使用。

 

      對於普通的Java類型,有許多內建的類型別名。它們都是大小寫不敏感的,由於重載的名字,要注意原生類型的特殊處理。

 

 

 

別名

映射的類型

_byte

byte

_long

long

_short

short

_int

int

_integer

int

_double

double

_float

float

_boolean

boolean

string

String

byte

Byte

long

Long

short

Short

int

Integer

integer

Integer

double

Double

float

Float

boolean

Boolean

date

Date

decimal

BigDecimal

bigdecimal

BigDecimal

object

Object

map

Map

hashmap

HashMap

list

List

arraylist

ArrayList

collection

Collection

iterator

Iterator

 

 

 

4.4 typeHandlers類型句柄

 

 

無論是MyBatis在預處理語句中設置一個參數,還是從結果集中取出一個值時,類型處理器被用來將獲取的值以合適的方式轉換成Java類型。下面這個表格描述了默認的類型處理器。

 

 

 

類型處理器

Java類型

JDBC類型

BooleanTypeHandler

Boolean,boolean

任何兼容的布爾值

ByteTypeHandler

Byte,byte

任何兼容的數字或字節類型

ShortTypeHandler

Short,short

任何兼容的數字或短整型

IntegerTypeHandler

Integer,int

任何兼容的數字和整型

LongTypeHandler

Long,long

任何兼容的數字或長整型

FloatTypeHandler

Float,float

任何兼容的數字或單精度浮點型

DoubleTypeHandler

Double,double

任何兼容的數字或雙精度浮點型

BigDecimalTypeHandler

BigDecimal

任何兼容的數字或十進制小數類型

StringTypeHandler

String

CHAR和VARCHAR類型

ClobTypeHandler

String

CLOB和LONGVARCHAR類型

NStringTypeHandler

String

NVARCHAR和NCHAR類型

NClobTypeHandler

String

NCLOB類型

ByteArrayTypeHandler

byte[]

任何兼容的字節流類型

BlobTypeHandler

byte[]

BLOB和LONGVARBINARY類型

DateTypeHandler

Date(java.util)

TIMESTAMP類型

DateOnlyTypeHandler

Date(java.util)

DATE類型

TimeOnlyTypeHandler

Date(java.util)

TIME類型

SqlTimestampTypeHandler

Timestamp(java.sql)

TIMESTAMP類型

SqlDateTypeHandler

Date(java.sql)

DATE類型

SqlTimeTypeHandler

Time(java.sql)

TIME類型

ObjectTypeHandler

Any

其他或未指定類型

EnumTypeHandler

Enumeration類型

VARCHAR-任何兼容的字符串類型,作為代碼存儲(而不是索引)。

 

 

 

你可以重寫類型處理器或創建你自己的類型處理器來處理不支持的或非標准的類型。要這樣做的話,簡單實現TypeHandler接口(org.mybatis.type),然后映射新的類型處理器類到Java類型,還有可選的一個JDBC類型。然后再typeHandlers中添加這個類型處理器。

新定義的類型處理器將會覆蓋已經存在的處理Java的String類型屬性和VARCHAR參數及結果的類型處理器。要注意MyBatis不會審視數據庫元信息來決定使用哪種類型,所以你必須在參數和結果映射中指定那是VARCHAR類型的字段,來綁定到正確的類型處理器上。這是因為MyBatis直到語句被執行都不知道數據類型的這個現實導致的。

 

 

 

Java代碼   收藏代碼
  1. public class LimingStringTypeHandler implements TypeHandler {  
  2.   
  3.     @Override  
  4.     public void setParameter(PreparedStatement ps, int i, Object parameter, JdbcType jdbcType) throws SQLException {  
  5.         System.out.println("setParameter - parameter: " + ((String) parameter) + ", jdbcType: " + jdbcType.TYPE_CODE);  
  6.         ps.setString(i, ((String) parameter));  
  7.     }  
  8.   
  9.     @Override  
  10.     public Object getResult(ResultSet rs, String columnName) throws SQLException {  
  11.         System.out.println("getResult - columnName: " + columnName);  
  12.         return rs.getString(columnName);  
  13.     }  
  14.   
  15.     @Override  
  16.     public Object getResult(CallableStatement cs, int columnIndex) throws SQLException {  
  17.         System.out.println("getResult - columnIndex: " + columnIndex);  
  18.         return cs.getString(columnIndex);  
  19.     }  
  20. }  
 

 

 

在配置文件的typeHandlers中添加typeHandler標簽。

 

 

Xml代碼   收藏代碼
  1. <typeHandlers>  
  2.     <typeHandler javaType="String" jdbcType="VARCHAR" handler="liming.student.manager.type.LimingStringTypeHandler"/>  
  3. </typeHandlers>  

 

 

 

 

4.5 ObjectFactory對象工廠

 

 

每次MyBatis 為結果對象創建一個新實例,都會用到ObjectFactory。默認的ObjectFactory 與使用目標類的構造函數創建一個實例毫無區別,如果有已經映射的參數,那也可能使用帶參數的構造函數。

如果你重寫ObjectFactory 的默認操作,你可以通過繼承org.apache.ibatis.reflection.factory.DefaultObjectFactory創建一下你自己的。

ObjectFactory接口很簡單。它包含兩個創建用的方法,一個是處理默認構造方法的,另外一個是處理帶參數構造方法的。最終,setProperties方法可以被用來配置ObjectFactory。在初始化你的ObjectFactory實例后,objectFactory元素體中定義的屬性會被傳遞給setProperties方法。

 

 

 

 

Java代碼   收藏代碼
  1. public class LimingObjectFactory extends DefaultObjectFactory {  
  2.   
  3.     private static final long serialVersionUID = -399284318168302833L;  
  4.   
  5.     @Override  
  6.     public Object create(Class type) {  
  7.         return super.create(type);  
  8.     }  
  9.   
  10.     @Override  
  11.     public Object create(Class type, List<Class> constructorArgTypes, List<Object> constructorArgs) {  
  12.         System.out.println("create - type: " + type.toString());  
  13.         return super.create(type, constructorArgTypes, constructorArgs);  
  14.     }  
  15.   
  16.     @Override  
  17.     public void setProperties(Properties properties) {  
  18.         System.out.println("setProperties - properties: " + properties.toString() + ", someProperty: " + properties.getProperty("someProperty"));  
  19.         super.setProperties(properties);  
  20.     }  
  21.   
  22. }  
 

 

 

配置文件中添加objectFactory標簽

 

 

Xml代碼   收藏代碼
  1. <objectFactory type="liming.student.manager.configuration.LimingObjectFactory">  
  2.     <property name="someProperty" value="100"/>  
  3. </objectFactory>  
 

 

 

4.6 plugins插件

 

 

MyBatis允許你在某一點攔截已映射語句執行的調用。默認情況下,MyBatis允許使用插件來攔截方法調用:

 

  • Executor(update, query, flushStatements, commit, rollback, getTransaction, close, isClosed)
  • ParameterHandler(getParameterObject, setParameters)
  • ResultSetHandler(handleResultSets, handleOutputParameters)
  • StatementHandler(prepare, parameterize, batch, update, query)

 

這些類中方法的詳情可以通過查看每個方法的簽名來發現,而且它們的源代碼在MyBatis的發行包中有。你應該理解你覆蓋方法的行為,假設你所做的要比監視調用要多。如果你嘗試修改或覆蓋一個給定的方法,你可能會打破MyBatis的核心。這是低層次的類和方法,要謹慎使用插件。

使用插件是它們提供的非常簡單的力量。簡單實現攔截器接口,要確定你想攔截的指定簽名。

 

 

 

4.7 environments環境

MyBatis 可以配置多個環境。這可以幫助你SQL 映射對應多種數據庫等。

 

 

 

4.8 mappers映射器

這里是告訴MyBatis 去哪尋找映射SQL 的語句。可以使用類路徑中的資源引用,或者使用字符,輸入確切的URL 引用。

例如:

 

 

Xml代碼   收藏代碼
  1. <mappers>  
  2.     <mapper resource="com/manager/data/maps/UserMapper.xml" />  
  3.     <mapper resource="com/manager/data/maps/StudentMapper.xml" />  
  4.     <mapper resource="com/manager/data/maps/ClassMapper.xml" />  
  5. </mappers>  


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM