MyBatis詳解 與配置MyBatis+Spring+MySql 1

MyBatis簡介

      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.javaeye.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>  

 

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. }  

 

         更詳細的功能源代碼http://limingnihao.javaeye.com/admin/blogs/782190頁面最下面;

二、SQL語句映射文件(1)resultMap

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>  

 

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


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

 

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="StudentEntity" id="studentResultMap">  
  2.     <id property="studentID" column="STUDENT_ID"/>  
  3.     <result property="studentName" column="STUDENT_NAME"/>  
  4.     <result property="studentSex" column="STUDENT_SEX"/>  
  5.     <result property="studentBirthday" column="STUDENT_BIRTHDAY"/>  
  6. </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文件部分內容中。

二、SQL語句映射文件(2)增刪改查、參數、緩存

 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());  

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


轉載:   http://limingnihao.iteye.com/blog/781671
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章