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中。
- /* 建立數據庫 */
- CREATE DATABASE STUDENT_MANAGER;
- USE STUDENT_MANAGER;
- /***** 建立student表 *****/
- CREATE TABLE STUDENT_TBL
- (
- STUDENT_ID VARCHAR(255) PRIMARY KEY,
- STUDENT_NAME VARCHAR(10) NOT NULL,
- STUDENT_SEX VARCHAR(10),
- STUDENT_BIRTHDAY DATE,
- CLASS_ID VARCHAR(255)
- );
- /*插入學生數據*/
- INSERT INTO STUDENT_TBL (STUDENT_ID,
- STUDENT_NAME,
- STUDENT_SEX,
- STUDENT_BIRTHDAY,
- CLASS_ID)
- VALUES (123456,
- '某某某',
- '女',
- '1980-08-01',
- 121546
- )
創建連接MySql使用的配置文件mysql.properties。
- jdbc.driverClassName=com.mysql.jdbc.Driver
- 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
- public class StudentEntity implements Serializable {
- private static final long serialVersionUID = 3096154202413606831L;
- private ClassEntity classEntity;
- private Date studentBirthday;
- private String studentID;
- private String studentName;
- private String studentSex;
- public ClassEntity getClassEntity() {
- return classEntity;
- }
- public Date getStudentBirthday() {
- return studentBirthday;
- }
- public String getStudentID() {
- return studentID;
- }
- public String getStudentName() {
- return studentName;
- }
- public String getStudentSex() {
- return studentSex;
- }
- public void setClassEntity(ClassEntity classEntity) {
- this.classEntity = classEntity;
- }
- public void setStudentBirthday(Date studentBirthday) {
- this.studentBirthday = studentBirthday;
- }
- public void setStudentID(String studentID) {
- this.studentID = studentID;
- }
- public void setStudentName(String studentName) {
- this.studentName = studentName;
- }
- public void setStudentSex(String studentSex) {
- this.studentSex = studentSex;
- }
- }
1.2.3.2創建數據訪問接口
Student類對應的dao接口:StudentMapper。
- public interface StudentMapper {
- public StudentEntity getStudent(String studentID);
- public StudentEntity getStudentAndClass(String studentID);
- public List<StudentEntity> getStudentAll();
- public void insertStudent(StudentEntity entity);
- public void deleteStudent(StudentEntity entity);
- public void updateStudent(StudentEntity entity);
- }
1.2.3.3創建SQL映射語句文件
Student類的sql語句文件StudentMapper.xml
resultMap標簽:表字段與屬性的映射。
Select標簽:查詢sql。
- <?xml version="1.0" encoding="UTF-8" ?>
- <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
- <mapper namespace="com.manager.data.StudentMapper">
- <resultMap type="StudentEntity" id="studentResultMap">
- <id property="studentID" column="STUDENT_ID"/>
- <result property="studentName" column="STUDENT_NAME"/>
- <result property="studentSex" column="STUDENT_SEX"/>
- <result property="studentBirthday" column="STUDENT_BIRTHDAY"/>
- </resultMap>
- <!-- 查詢學生,根據id -->
- <select id="getStudent" parameterType="String" resultType="StudentEntity" resultMap="studentResultMap">
- <![CDATA[
- SELECT * from STUDENT_TBL ST
- WHERE ST.STUDENT_ID = #{studentID}
- ]]>
- </select>
- <!-- 查詢學生列表 -->
- <select id="getStudentAll" resultType="com.manager.data.model.StudentEntity" resultMap="studentResultMap">
- <![CDATA[
- SELECT * from STUDENT_TBL
- ]]>
- </select>
- </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 version="1.0" encoding="UTF-8" ?>
- <!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config 3.0//EN" "http://mybatis.org/dtd/mybatis-3-config.dtd">
- <configuration>
- <typeAliases>
- <typeAlias alias="StudentEntity" type="com.manager.data.model.StudentEntity"/>
- </typeAliases>
- <mappers>
- <mapper resource="com/manager/data/maps/StudentMapper.xml" />
- </mappers>
- </configuration>
1.2.3.5修改Spring 的配置文件
主要是添加SqlSession的制作工廠類的bean:SqlSessionFactoryBean,(在mybatis.spring包中)。需要指定配置文件位置和dataSource。
和數據訪問接口對應的實現bean。通過MapperFactoryBean創建出來。需要執行接口類全稱和SqlSession工廠bean的引用。
- <!-- 導入屬性配置文件 -->
- <context:property-placeholder location="classpath:mysql.properties" />
- <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
- <property name="driverClassName" value="${jdbc.driverClassName}" />
- <property name="url" value="${jdbc.url}" />
- </bean>
- <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
- <property name="dataSource" ref="dataSource" />
- </bean>
- <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
- <property name="configLocation" value="classpath:mybatis-config.xml" />
- <property name="dataSource" ref="dataSource" />
- </bean>
- <!— mapper bean -->
- <bean id="studentMapper" class="org.mybatis.spring.MapperFactoryBean">
- <property name="mapperInterface" value="com.manager.data.StudentMapper" />
- <property name="sqlSessionFactory" ref="sqlSessionFactory" />
- </bean>
也可以不定義mapper的bean,使用注解:
將StudentMapper加入注解
- @Repository
- @Transactional
- public interface StudentMapper {
- }
對應的需要在dispatcher-servlet.xml中加入掃描:
- <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
- <property name="annotationClass" value="org.springframework.stereotype.Repository"/>
- <property name="basePackage" value="com.liming.manager"/>
- <property name="sqlSessionFactory" ref="sqlSessionFactory"/>
- </bean>
1.2.4測試StudentMapper
使用SpringMVC測試,創建一個TestController,配置tomcat,訪問index.do頁面進行測試:
- @Controller
- public class TestController {
- @Autowired
- private StudentMapper studentMapper;
- @RequestMapping(value = "index.do")
- public void indexPage() {
- StudentEntity entity = studentMapper.getStudent("10000013");
- System.out.println("name:" + entity.getStudentName());
- }
- }
使用Junit測試:
- 使用Junit測試:
- Java代碼
- @RunWith(value = SpringJUnit4ClassRunner.class)
- @ContextConfiguration(value = "test-servlet.xml")
- public class StudentMapperTest {
- @Autowired
- private ClassMapper classMapper;
- @Autowired
- private StudentMapper studentMapper;
- @Transactional
- public void getStudentTest(){
- StudentEntity entity = studentMapper.getStudent("10000013");
- System.out.println("" + entity.getStudentID() + entity.getStudentName());
- List<StudentEntity> studentList = studentMapper.getStudentAll();
- for( StudentEntity entityTemp : studentList){
- System.out.println(entityTemp.getStudentName());
- }
- }
- }
SQL 映射XML 文件是所有sql語句放置的地方。需要定義一個workspace,一般定義為對應的接口類的路徑。寫好SQL語句映射文件后,需要在MyBAtis配置文件mappers標簽中引用,例如:
- <mappers>
- <mapper resource="com/liming/manager/data/mappers/UserMapper.xml" />
- <mapper resource="com/liming/manager/data/mappers/StudentMapper.xml" />
- <mapper resource="com/liming/manager/data/mappers/ClassMapper.xml" />
- <mapper resource="com/liming/manager/data/mappers/TeacherMapper.xml" />
- </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 resultMapresultMap 是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其他基本數據庫表字段到實體類屬性的映射。
最簡單的例子:
- <resultMap type="liming.student.manager.data.model.StudentEntity" id="studentResultMap">
- <id property="studentId" column="STUDENT_ID" javaType="String" jdbcType="VARCHAR"/>
- <result property="studentName" column="STUDENT_NAME" javaType="String" jdbcType="VARCHAR"/>
- <result property="studentSex" column="STUDENT_SEX" javaType="int" jdbcType="INTEGER"/>
- <result property="studentBirthday" column="STUDENT_BIRTHDAY" javaType="Date" jdbcType="DATE"/>
- <result property="studentPhoto" column="STUDENT_PHOTO" javaType="byte[]" jdbcType="BLOB" typeHandler="org.apache.ibatis.type.BlobTypeHandler" />
- </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實現的功能就可以改為:
- <resultMap type="StudentEntity" id="studentResultMap" >
- <constructor>
- <idArg javaType="String" column="STUDENT_ID"/>
- <arg javaType="String" column="STUDENT_NAME"/>
- <arg javaType="String" column="STUDENT_SEX"/>
- <arg javaType="Date" column="STUDENT_BIRTHDAY"/>
- </constructor>
- </resultMap>
當然,我們需要定義StudentEntity實體類的構造方法:
- public StudentEntity(String studentID, String studentName, String studentSex, Date studentBirthday){
- this.studentID = studentID;
- this.studentName = studentName;
- this.studentSex = studentSex;
- this.studentBirthday = studentBirthday;
- }
2.1.3 association聯合
聯合元素用來處理“一對一”的關系。需要指定映射的Java實體類的屬性,屬性的javaType(通常MyBatis 自己會識別)。對應的數據庫表的列名稱。如果想覆寫的話返回結果的值,需要指定typeHandler。
不同情況需要告訴MyBatis 如何加載一個聯合。MyBatis 可以用兩種方式加載:
1. select: 執行一個其它映射的SQL 語句返回一個Java實體類型。較靈活;
2. resultsMap: 使用一個嵌套的結果映射來處理通過join查詢結果集,映射成Java實體類型。
例如,一個班級對應一個班主任。
首先定義好班級中的班主任屬性:
2.1.3.1使用select實現聯合
例:班級實體類中有班主任的屬性,通過聯合在得到一個班級實體時,同時映射出班主任實體。
這樣可以直接復用在TeacherMapper.xml文件中定義好的查詢teacher根據其ID的select語句。而且不需要修改寫好的SQL語句,只需要直接修改resultMap即可。
ClassMapper.xml文件部分內容:
- <resultMap type="ClassEntity" id="classResultMap">
- <id property="classID" column="CLASS_ID" />
- <result property="className" column="CLASS_NAME" />
- <result property="classYear" column="CLASS_YEAR" />
- <association property="teacherEntity" column="TEACHER_ID" select="getTeacher"/>
- </resultMap>
- <select id="getClassByID" parameterType="String" resultMap="classResultMap">
- SELECT * FROM CLASS_TBL CT
- WHERE CT.CLASS_ID = #{classID};
- </select>
TeacherMapper.xml文件部分內容:
- <resultMap type="TeacherEntity" id="teacherResultMap">
- <id property="teacherID" column="TEACHER_ID" />
- <result property="teacherName" column="TEACHER_NAME" />
- <result property="teacherSex" column="TEACHER_SEX" />
- <result property="teacherBirthday" column="TEACHER_BIRTHDAY"/>
- <result property="workDate" column="WORK_DATE"/>
- <result property="professional" column="PROFESSIONAL"/>
- </resultMap>
- <select id="getTeacher" parameterType="String" resultMap="teacherResultMap">
- SELECT *
- FROM TEACHER_TBL TT
- WHERE TT.TEACHER_ID = #{teacherID}
- </select>
2.1.3.2使用resultMap實現聯合
與上面同樣的功能,查詢班級,同時查詢器班主任。需在association中添加resultMap(在teacher的xml文件中定義好的),新寫sql(查詢班級表left join教師表),不需要teacher的select。
修改ClassMapper.xml文件部分內容:
- <resultMap type="ClassEntity" id="classResultMap">
- <id property="classID" column="CLASS_ID" />
- <result property="className" column="CLASS_NAME" />
- <result property="classYear" column="CLASS_YEAR" />
- <association property="teacherEntity" column="TEACHER_ID" resultMap="teacherResultMap"/>
- </resultMap>
- <select id="getClassAndTeacher" parameterType="String" resultMap="classResultMap">
- SELECT *
- FROM CLASS_TBL CT LEFT JOIN TEACHER_TBL TT ON CT.TEACHER_ID = TT.TEACHER_ID
- WHERE CT.CLASS_ID = #{classID};
- </select>
其中的teacherResultMap請見上面TeacherMapper.xml文件部分內容中。
2.1.4 collection聚集
聚集元素用來處理“一對多”的關系。需要指定映射的Java實體類的屬性,屬性的javaType(一般為ArrayList);列表中對象的類型ofType(Java實體類);對應的數據庫表的列名稱;
不同情況需要告訴MyBatis 如何加載一個聚集。MyBatis 可以用兩種方式加載:
1. select: 執行一個其它映射的SQL 語句返回一個Java實體類型。較靈活;
2. resultsMap: 使用一個嵌套的結果映射來處理通過join查詢結果集,映射成Java實體類型。
例如,一個班級有多個學生。
首先定義班級中的學生列表屬性:
2.1.4.1使用select實現聚集
用法和聯合很類似,區別在於,這是一對多,所以一般映射過來的都是列表。所以這里需要定義javaType為ArrayList,還需要定義列表中對象的類型ofType,以及必須設置的select的語句名稱(需要注意的是,這里的查詢student的select語句條件必須是外鍵classID)。
ClassMapper.xml文件部分內容:
- <resultMap type="ClassEntity" id="classResultMap">
- <id property="classID" column="CLASS_ID" />
- <result property="className" column="CLASS_NAME" />
- <result property="classYear" column="CLASS_YEAR" />
- <association property="teacherEntity" column="TEACHER_ID" select="getTeacher"/>
- <collection property="studentList" column="CLASS_ID" javaType="ArrayList" ofType="StudentEntity" select="getStudentByClassID"/>
- </resultMap>
- <select id="getClassByID" parameterType="String" resultMap="classResultMap">
- SELECT * FROM CLASS_TBL CT
- WHERE CT.CLASS_ID = #{classID};
- </select>
StudentMapper.xml文件部分內容:
- <!-- java屬性,數據庫表字段之間的映射定義 -->
- <resultMap type="StudentEntity" id="studentResultMap">
- <id property="studentID" column="STUDENT_ID" />
- <result property="studentName" column="STUDENT_NAME" />
- <result property="studentSex" column="STUDENT_SEX" />
- <result property="studentBirthday" column="STUDENT_BIRTHDAY" />
- </resultMap>
- <!-- 查詢學生list,根據班級id -->
- <select id="getStudentByClassID" parameterType="String" resultMap="studentResultMap">
- <include refid="selectStudentAll" />
- WHERE ST.CLASS_ID = #{classID}
- </select>
2.1.4.2使用resultMap實現聚集
使用resultMap,就需要重寫一個sql,left join學生表。
- <resultMap type="ClassEntity" id="classResultMap">
- <id property="classID" column="CLASS_ID" />
- <result property="className" column="CLASS_NAME" />
- <result property="classYear" column="CLASS_YEAR" />
- <association property="teacherEntity" column="TEACHER_ID" resultMap="teacherResultMap"/>
- <collection property="studentList" column="CLASS_ID" javaType="ArrayList" ofType="StudentEntity" resultMap="studentResultMap"/>
- </resultMap>
- <select id="getClassAndTeacherStudent" parameterType="String" resultMap="classResultMap">
- SELECT *
- FROM CLASS_TBL CT
- LEFT JOIN STUDENT_TBL ST
- ON CT.CLASS_ID = ST.CLASS_ID
- LEFT JOIN TEACHER_TBL TT
- ON CT.TEACHER_ID = TT.TEACHER_ID
- WHERE CT.CLASS_ID = #{classID};
- </select>
其中的teacherResultMap請見上面TeacherMapper.xml文件部分內容中。studentResultMap請見上面StudentMapper.xml文件部分內容中。
2.1.5discriminator鑒別器
有時一個單獨的數據庫查詢也許返回很多不同(但是希望有些關聯)數據類型的結果集。鑒別器元素就是被設計來處理這個情況的,還有包括類的繼承層次結構。鑒別器非常容易理解,因為它的表現很像Java語言中的switch語句。
定義鑒別器指定了column和javaType屬性。列是MyBatis查找比較值的地方。JavaType是需要被用來保證等價測試的合適類型(盡管字符串在很多情形下都會有用)。
下面這個例子為,當classId為20000001時,才映射classId屬性。
- <resultMap type="liming.student.manager.data.model.StudentEntity" id="resultMap_studentEntity_discriminator">
- <id property="studentId" column="STUDENT_ID" javaType="String" jdbcType="VARCHAR"/>
- <result property="studentName" column="STUDENT_NAME" javaType="String" jdbcType="VARCHAR"/>
- <result property="studentSex" column="STUDENT_SEX" javaType="int" jdbcType="INTEGER"/>
- <result property="studentBirthday" column="STUDENT_BIRTHDAY" javaType="Date" jdbcType="DATE"/>
- <result property="studentPhoto" column="STUDENT_PHOTO" javaType="byte[]" jdbcType="BLOB" typeHandler="org.apache.ibatis.type.BlobTypeHandler" />
- <result property="placeId" column="PLACE_ID" javaType="String" jdbcType="VARCHAR"/>
- <discriminator column="CLASS_ID" javaType="String" jdbcType="VARCHAR">
- <case value="20000001" resultType="liming.student.manager.data.model.StudentEntity" >
- <result property="classId" column="CLASS_ID" javaType="String" jdbcType="VARCHAR"/>
- </case>
- </discriminator>
- </resultMap>
2.2 select
一個select 元素非常簡單。例如:
- <!-- 查詢學生,根據id -->
- <select id="getStudent" parameterType="String" resultMap="studentResultMap">
- SELECT ST.STUDENT_ID,
- ST.STUDENT_NAME,
- ST.STUDENT_SEX,
- ST.STUDENT_BIRTHDAY,
- ST.CLASS_ID
- FROM STUDENT_TBL ST
- WHERE ST.STUDENT_ID = #{studentID}
- </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語句:
- <!-- 插入學生 -->
- <insert id="insertStudent" parameterType="StudentEntity">
- INSERT INTO STUDENT_TBL (STUDENT_ID,
- STUDENT_NAME,
- STUDENT_SEX,
- STUDENT_BIRTHDAY,
- CLASS_ID)
- VALUES (#{studentID},
- #{studentName},
- #{studentSex},
- #{studentBirthday},
- #{classEntity.classID})
- </insert>
insert可以使用數據庫支持的自動生成主鍵策略,設置useGeneratedKeys=”true”,然后把keyProperty 設成對應的列,就搞定了。比如說上面的StudentEntity 使用auto-generated 為id 列生成主鍵.
還可以使用selectKey元素。下面例子,使用mysql數據庫nextval('student')為自定義函數,用來生成一個key。
- <!-- 插入學生 自動主鍵-->
- <insert id="insertStudentAutoKey" parameterType="StudentEntity">
- <selectKey keyProperty="studentID" resultType="String" order="BEFORE">
- select nextval('student')
- </selectKey>
- INSERT INTO STUDENT_TBL (STUDENT_ID,
- STUDENT_NAME,
- STUDENT_SEX,
- STUDENT_BIRTHDAY,
- CLASS_ID)
- VALUES (#{studentID},
- #{studentName},
- #{studentSex},
- #{studentBirthday},
- #{classEntity.classID})
- </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:
- <!-- 更新學生信息 -->
- <update id="updateStudent" parameterType="StudentEntity">
- UPDATE STUDENT_TBL
- SET STUDENT_TBL.STUDENT_NAME = #{studentName},
- STUDENT_TBL.STUDENT_SEX = #{studentSex},
- STUDENT_TBL.STUDENT_BIRTHDAY = #{studentBirthday},
- STUDENT_TBL.CLASS_ID = #{classEntity.classID}
- WHERE STUDENT_TBL.STUDENT_ID = #{studentID};
- </update>
一個簡單的delete:
- <!-- 刪除學生 -->
- <delete id="deleteStudent" parameterType="StudentEntity">
- DELETE FROM STUDENT_TBL WHERE STUDENT_ID = #{studentID}
- </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 語句段,供其它語句調用。比如:
- <!-- 復用sql語句 查詢student表所有字段 -->
- <sql id="selectStudentAll">
- SELECT ST.STUDENT_ID,
- ST.STUDENT_NAME,
- ST.STUDENT_SEX,
- ST.STUDENT_BIRTHDAY,
- ST.CLASS_ID
- FROM STUDENT_TBL ST
- </sql>
這樣,在select的語句中就可以直接引用使用了,將上面select語句改成:
- <!-- 查詢學生,根據id -->
- <select id="getStudent" parameterType="String" resultMap="studentResultMap">
- <include refid="selectStudentAll"/>
- WHERE ST.STUDENT_ID = #{studentID}
- </select>
2.6parameters
上面很多地方已經用到了參數,比如查詢、修改、刪除的條件,插入,修改的數據等,MyBatis可以使用的基本數據類型和Java的復雜數據類型。
基本數據類型,String,int,date等。
但是使用基本數據類型,只能提供一個參數,所以需要使用Java實體類,或Map類型做參數類型。通過#{}可以直接得到其屬性。
2.6.1基本類型參數
根據入學時間,檢索學生列表:
- <!-- 查詢學生list,根據入學時間 -->
- <select id="getStudentListByDate" parameterType="Date" resultMap="studentResultMap">
- SELECT *
- FROM STUDENT_TBL ST LEFT JOIN CLASS_TBL CT ON ST.CLASS_ID = CT.CLASS_ID
- WHERE CT.CLASS_YEAR = #{classYear};
- </select>
- List<StudentEntity> studentList = studentMapper.getStudentListByClassYear(StringUtil.parse("2007-9-1"));
- for (StudentEntity entityTemp : studentList) {
- System.out.println(entityTemp.toString());
- }
2.6.2Java實體類型參數
根據姓名和性別,檢索學生列表。使用實體類做參數:
- <!-- 查詢學生list,like姓名、=性別,參數entity類型 -->
- <select id="getStudentListWhereEntity" parameterType="StudentEntity" resultMap="studentResultMap">
- SELECT * from STUDENT_TBL ST
- WHERE ST.STUDENT_NAME LIKE CONCAT(CONCAT('%', #{studentName}),'%')
- AND ST.STUDENT_SEX = #{studentSex}
- </select>
- StudentEntity entity = new StudentEntity();
- entity.setStudentName("李");
- entity.setStudentSex("男");
- List<StudentEntity> studentList = studentMapper.getStudentListWhereEntity(entity);
- for (StudentEntity entityTemp : studentList) {
- System.out.println(entityTemp.toString());
- }
2.6.3Map參數
根據姓名和性別,檢索學生列表。使用Map做參數:
- <!-- 查詢學生list,=性別,參數map類型 -->
- <select id="getStudentListWhereMap" parameterType="Map" resultMap="studentResultMap">
- SELECT * from STUDENT_TBL ST
- WHERE ST.STUDENT_SEX = #{sex}
- AND ST.STUDENT_SEX = #{sex}
- </select>
- Map<String, String> map = new HashMap<String, String>();
- map.put("sex", "女");
- map.put("name", "李");
- List<StudentEntity> studentList = studentMapper.getStudentListWhereMap(map);
- for (StudentEntity entityTemp : studentList) {
- System.out.println(entityTemp.toString());
- }
2.6.4多參數的實現
如果想傳入多個參數,則需要在接口的參數上添加@Param注解。給出一個實例:
接口寫法:
- 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寫法:
- <!-- 查詢學生list,like姓名、=性別、=生日、=班級,多參數方式 -->
- <select id="getStudentListWhereParam" resultMap="studentResultMap">
- SELECT * from STUDENT_TBL ST
- <where>
- <if test="name!=null and name!='' ">
- ST.STUDENT_NAME LIKE CONCAT(CONCAT('%', #{name}),'%')
- </if>
- <if test="sex!= null and sex!= '' ">
- AND ST.STUDENT_SEX = #{sex}
- </if>
- <if test="birthday!=null">
- AND ST.STUDENT_BIRTHDAY = #{birthday}
- </if>
- <if test="classEntity!=null and classEntity.classID !=null and classEntity.classID!='' ">
- AND ST.CLASS_ID = #{classEntity.classID}
- </if>
- </where>
- </select>
進行查詢:
- List<StudentEntity> studentList = studentMapper.getStudentListWhereParam("", "",StringUtil.parse("1985-05-28"), classMapper.getClassByID("20000002"));
- for (StudentEntity entityTemp : studentList) {
- System.out.println(entityTemp.toString());
- }
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 個對象結果或列表引用,並且返回的結果是只讀。因為在不用的線程里的兩個調用者修改它們可能會導致引用沖突。
- <cache eviction="FIFO" flushInterval="60000" size="512" readOnly="true">
- </cache>
還可以在不同的命名空間里共享同一個緩存配置或者實例。在這種情況下,你就可以使用cache-ref 來引用另外一個緩存。
- <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。
- <!-- 插入學生 自動主鍵-->
- <insert id="createStudentAutoKey" parameterType="liming.student.manager.data.model.StudentEntity" keyProperty="studentId">
- <selectKey keyProperty="studentId" resultType="String" order="BEFORE">
- select nextval('student')
- </selectKey>
- INSERT INTO STUDENT_TBL(STUDENT_ID,
- STUDENT_NAME,
- STUDENT_SEX,
- STUDENT_BIRTHDAY,
- STUDENT_PHOTO,
- CLASS_ID,
- PLACE_ID)
- VALUES (#{studentId},
- #{studentName},
- #{studentSex},
- #{studentBirthday},
- #{studentPhoto, javaType=byte[], jdbcType=BLOB, typeHandler=org.apache.ibatis.type.BlobTypeHandler},
- #{classId},
- #{placeId})
- </insert>
調用接口方法,和獲取自動生成key
- StudentEntity entity = new StudentEntity();
- entity.setStudentName("黎明你好");
- entity.setStudentSex(1);
- entity.setStudentBirthday(DateUtil.parse("1985-05-28"));
- entity.setClassId("20000001");
- entity.setPlaceId("70000001");
- this.dynamicSqlMapper.createStudentAutoKey(entity);
- 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語句中,我們以查詢為例。首先看一個很普通的查詢:
- <!-- 查詢學生list,like姓名 -->
- <select id="getStudentListLikeName" parameterType="StudentEntity" resultMap="studentResultMap">
- SELECT * from STUDENT_TBL ST
- WHERE ST.STUDENT_NAME LIKE CONCAT(CONCAT('%', #{studentName}),'%')
- </select>
但是此時如果studentName或studentSex為null,此語句很可能報錯或查詢結果為空。此時我們使用if動態sql語句先進行判斷,如果值為null或等於空字符串,我們就不進行此條件的判斷,增加靈活性。
參數為實體類StudentEntity。將實體類中所有的屬性均進行判斷,如果不為空則執行判斷條件。
- <!-- 2 if(判斷參數) - 將實體類不為空的屬性作為where條件 -->
- <select id="getStudentList_if" resultMap="resultMap_studentEntity" parameterType="liming.student.manager.data.model.StudentEntity">
- SELECT ST.STUDENT_ID,
- ST.STUDENT_NAME,
- ST.STUDENT_SEX,
- ST.STUDENT_BIRTHDAY,
- ST.STUDENT_PHOTO,
- ST.CLASS_ID,
- ST.PLACE_ID
- FROM STUDENT_TBL ST
- WHERE
- <if test="studentName !=null ">
- ST.STUDENT_NAME LIKE CONCAT(CONCAT('%', #{studentName, jdbcType=VARCHAR}),'%')
- </if>
- <if test="studentSex != null and studentSex != '' ">
- AND ST.STUDENT_SEX = #{studentSex, jdbcType=INTEGER}
- </if>
- <if test="studentBirthday != null ">
- AND ST.STUDENT_BIRTHDAY = #{studentBirthday, jdbcType=DATE}
- </if>
- <if test="classId != null and classId!= '' ">
- AND ST.CLASS_ID = #{classId, jdbcType=VARCHAR}
- </if>
- <if test="classEntity != null and classEntity.classId !=null and classEntity.classId !=' ' ">
- AND ST.CLASS_ID = #{classEntity.classId, jdbcType=VARCHAR}
- </if>
- <if test="placeId != null and placeId != '' ">
- AND ST.PLACE_ID = #{placeId, jdbcType=VARCHAR}
- </if>
- <if test="placeEntity != null and placeEntity.placeId != null and placeEntity.placeId != '' ">
- AND ST.PLACE_ID = #{placeEntity.placeId, jdbcType=VARCHAR}
- </if>
- <if test="studentId != null and studentId != '' ">
- AND ST.STUDENT_ID = #{studentId, jdbcType=VARCHAR}
- </if>
- </select>
使用時比較靈活, new一個這樣的實體類,我們需要限制那個條件,只需要附上相應的值就會where這個條件,相反不去賦值就可以不在where中判斷。
- public void select_test_2_1() {
- StudentEntity entity = new StudentEntity();
- entity.setStudentName("");
- entity.setStudentSex(1);
- entity.setStudentBirthday(DateUtil.parse("1985-05-28"));
- entity.setClassId("20000001");
- //entity.setPlaceId("70000001");
- List<StudentEntity> list = this.dynamicSqlMapper.getStudentList_if(entity);
- for (StudentEntity e : list) {
- System.out.println(e.toString());
- }
- }
3.3 if + where 的條件判斷
當where中的條件使用的if標簽較多時,這樣的組合可能會導致錯誤。我們以在3.1中的查詢語句為例子,當java代碼按如下方法調用時:
- @Test
- public void select_test_2_1() {
- StudentEntity entity = new StudentEntity();
- entity.setStudentName(null);
- entity.setStudentSex(1);
- List<StudentEntity> list = this.dynamicSqlMapper.getStudentList_if(entity);
- for (StudentEntity e : list) {
- System.out.println(e.toString());
- }
- }
如果上面例子,參數studentName為null,將不會進行STUDENT_NAME列的判斷,則會直接導“WHERE AND”關鍵字多余的錯誤SQL。
這時我們可以使用where動態語句來解決。這個“where”標簽會知道如果它包含的標簽中有返回值的話,它就插入一個‘where’。此外,如果標簽返回的內容是以AND 或OR 開頭的,則它會剔除掉。
上面例子修改為:
- <!-- 3 select - where/if(判斷參數) - 將實體類不為空的屬性作為where條件 -->
- <select id="getStudentList_whereIf" resultMap="resultMap_studentEntity" parameterType="liming.student.manager.data.model.StudentEntity">
- SELECT ST.STUDENT_ID,
- ST.STUDENT_NAME,
- ST.STUDENT_SEX,
- ST.STUDENT_BIRTHDAY,
- ST.STUDENT_PHOTO,
- ST.CLASS_ID,
- ST.PLACE_ID
- FROM STUDENT_TBL ST
- <where>
- <if test="studentName !=null ">
- ST.STUDENT_NAME LIKE CONCAT(CONCAT('%', #{studentName, jdbcType=VARCHAR}),'%')
- </if>
- <if test="studentSex != null and studentSex != '' ">
- AND ST.STUDENT_SEX = #{studentSex, jdbcType=INTEGER}
- </if>
- <if test="studentBirthday != null ">
- AND ST.STUDENT_BIRTHDAY = #{studentBirthday, jdbcType=DATE}
- </if>
- <if test="classId != null and classId!= '' ">
- AND ST.CLASS_ID = #{classId, jdbcType=VARCHAR}
- </if>
- <if test="classEntity != null and classEntity.classId !=null and classEntity.classId !=' ' ">
- AND ST.CLASS_ID = #{classEntity.classId, jdbcType=VARCHAR}
- </if>
- <if test="placeId != null and placeId != '' ">
- AND ST.PLACE_ID = #{placeId, jdbcType=VARCHAR}
- </if>
- <if test="placeEntity != null and placeEntity.placeId != null and placeEntity.placeId != '' ">
- AND ST.PLACE_ID = #{placeEntity.placeId, jdbcType=VARCHAR}
- </if>
- <if test="studentId != null and studentId != '' ">
- AND ST.STUDENT_ID = #{studentId, jdbcType=VARCHAR}
- </if>
- </where>
- </select>
3.4 if + set 的更新語句
當update語句中沒有使用if標簽時,如果有一個參數為null,都會導致錯誤。
當在update語句中使用if標簽時,如果前面的if沒有執行,則或導致逗號多余錯誤。使用set標簽可以將動態的配置SET 關鍵字,和剔除追加到條件末尾的任何不相關的逗號。
使用if+set標簽修改后,如果某項為null則不進行更新,而是保持數據庫原值。如下示例:
- <!-- 4 if/set(判斷參數) - 將實體類不為空的屬性更新 -->
- <update id="updateStudent_if_set" parameterType="liming.student.manager.data.model.StudentEntity">
- UPDATE STUDENT_TBL
- <set>
- <if test="studentName != null and studentName != '' ">
- STUDENT_TBL.STUDENT_NAME = #{studentName},
- </if>
- <if test="studentSex != null and studentSex != '' ">
- STUDENT_TBL.STUDENT_SEX = #{studentSex},
- </if>
- <if test="studentBirthday != null ">
- STUDENT_TBL.STUDENT_BIRTHDAY = #{studentBirthday},
- </if>
- <if test="studentPhoto != null ">
- STUDENT_TBL.STUDENT_PHOTO = #{studentPhoto, javaType=byte[], jdbcType=BLOB, typeHandler=org.apache.ibatis.type.BlobTypeHandler},
- </if>
- <if test="classId != '' ">
- STUDENT_TBL.CLASS_ID = #{classId}
- </if>
- <if test="placeId != '' ">
- STUDENT_TBL.PLACE_ID = #{placeId}
- </if>
- </set>
- WHERE STUDENT_TBL.STUDENT_ID = #{studentId};
- </update>
3.5 if + trim代替where/set標簽
trim是更靈活的去處多余關鍵字的標簽,他可以實踐where和set的效果。
3.5.1trim代替where
- <!-- 5.1 if/trim代替where(判斷參數) - 將實體類不為空的屬性作為where條件 -->
- <select id="getStudentList_if_trim" resultMap="resultMap_studentEntity">
- SELECT ST.STUDENT_ID,
- ST.STUDENT_NAME,
- ST.STUDENT_SEX,
- ST.STUDENT_BIRTHDAY,
- ST.STUDENT_PHOTO,
- ST.CLASS_ID,
- ST.PLACE_ID
- FROM STUDENT_TBL ST
- <trim prefix="WHERE" prefixOverrides="AND|OR">
- <if test="studentName !=null ">
- ST.STUDENT_NAME LIKE CONCAT(CONCAT('%', #{studentName, jdbcType=VARCHAR}),'%')
- </if>
- <if test="studentSex != null and studentSex != '' ">
- AND ST.STUDENT_SEX = #{studentSex, jdbcType=INTEGER}
- </if>
- <if test="studentBirthday != null ">
- AND ST.STUDENT_BIRTHDAY = #{studentBirthday, jdbcType=DATE}
- </if>
- <if test="classId != null and classId!= '' ">
- AND ST.CLASS_ID = #{classId, jdbcType=VARCHAR}
- </if>
- <if test="classEntity != null and classEntity.classId !=null and classEntity.classId !=' ' ">
- AND ST.CLASS_ID = #{classEntity.classId, jdbcType=VARCHAR}
- </if>
- <if test="placeId != null and placeId != '' ">
- AND ST.PLACE_ID = #{placeId, jdbcType=VARCHAR}
- </if>
- <if test="placeEntity != null and placeEntity.placeId != null and placeEntity.placeId != '' ">
- AND ST.PLACE_ID = #{placeEntity.placeId, jdbcType=VARCHAR}
- </if>
- <if test="studentId != null and studentId != '' ">
- AND ST.STUDENT_ID = #{studentId, jdbcType=VARCHAR}
- </if>
- </trim>
- </select>
3.5.2 trim代替set
- <!-- 5.2 if/trim代替set(判斷參數) - 將實體類不為空的屬性更新 -->
- <update id="updateStudent_if_trim" parameterType="liming.student.manager.data.model.StudentEntity">
- UPDATE STUDENT_TBL
- <trim prefix="SET" suffixOverrides=",">
- <if test="studentName != null and studentName != '' ">
- STUDENT_TBL.STUDENT_NAME = #{studentName},
- </if>
- <if test="studentSex != null and studentSex != '' ">
- STUDENT_TBL.STUDENT_SEX = #{studentSex},
- </if>
- <if test="studentBirthday != null ">
- STUDENT_TBL.STUDENT_BIRTHDAY = #{studentBirthday},
- </if>
- <if test="studentPhoto != null ">
- STUDENT_TBL.STUDENT_PHOTO = #{studentPhoto, javaType=byte[], jdbcType=BLOB, typeHandler=org.apache.ibatis.type.BlobTypeHandler},
- </if>
- <if test="classId != '' ">
- STUDENT_TBL.CLASS_ID = #{classId},
- </if>
- <if test="placeId != '' ">
- STUDENT_TBL.PLACE_ID = #{placeId}
- </if>
- </trim>
- WHERE STUDENT_TBL.STUDENT_ID = #{studentId}
- </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包起來,放置關鍵字多於錯誤。
- <!-- 6 choose(判斷參數) - 按順序將實體類第一個不為空的屬性作為where條件 -->
- <select id="getStudentList_choose" resultMap="resultMap_studentEntity" parameterType="liming.student.manager.data.model.StudentEntity">
- SELECT ST.STUDENT_ID,
- ST.STUDENT_NAME,
- ST.STUDENT_SEX,
- ST.STUDENT_BIRTHDAY,
- ST.STUDENT_PHOTO,
- ST.CLASS_ID,
- ST.PLACE_ID
- FROM STUDENT_TBL ST
- <where>
- <choose>
- <when test="studentName !=null ">
- ST.STUDENT_NAME LIKE CONCAT(CONCAT('%', #{studentName, jdbcType=VARCHAR}),'%')
- </when >
- <when test="studentSex != null and studentSex != '' ">
- AND ST.STUDENT_SEX = #{studentSex, jdbcType=INTEGER}
- </when >
- <when test="studentBirthday != null ">
- AND ST.STUDENT_BIRTHDAY = #{studentBirthday, jdbcType=DATE}
- </when >
- <when test="classId != null and classId!= '' ">
- AND ST.CLASS_ID = #{classId, jdbcType=VARCHAR}
- </when >
- <when test="classEntity != null and classEntity.classId !=null and classEntity.classId !=' ' ">
- AND ST.CLASS_ID = #{classEntity.classId, jdbcType=VARCHAR}
- </when >
- <when test="placeId != null and placeId != '' ">
- AND ST.PLACE_ID = #{placeId, jdbcType=VARCHAR}
- </when >
- <when test="placeEntity != null and placeEntity.placeId != null and placeEntity.placeId != '' ">
- AND ST.PLACE_ID = #{placeEntity.placeId, jdbcType=VARCHAR}
- </when >
- <when test="studentId != null and studentId != '' ">
- AND ST.STUDENT_ID = #{studentId, jdbcType=VARCHAR}
- </when >
- <otherwise>
- </otherwise>
- </choose>
- </where>
- </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示例的寫法
接口的方法聲明:
動態SQL語句:
- <!— 7.1 foreach(循環array參數) - 作為where中in的條件 -->
- <select id="getStudentListByClassIds_foreach_array" resultMap="resultMap_studentEntity">
- SELECT ST.STUDENT_ID,
- ST.STUDENT_NAME,
- ST.STUDENT_SEX,
- ST.STUDENT_BIRTHDAY,
- ST.STUDENT_PHOTO,
- ST.CLASS_ID,
- ST.PLACE_ID
- FROM STUDENT_TBL ST
- WHERE ST.CLASS_ID IN
- <foreach collection="array" item="classIds" open="(" separator="," close=")">
- #{classIds}
- </foreach>
- </select>
測試代碼,查詢學生中,在20000001、20000002這兩個班級的學生:
- @Test
- public void test7_foreach() {
- String[] classIds = { "20000001", "20000002" };
- List<StudentEntity> list = this.dynamicSqlMapper.getStudentListByClassIds_foreach_array(classIds);
- for (StudentEntity e : list) {
- System.out.println(e.toString());
- }
- <p>}<span style="font-size: 14px; font-weight: bold; white-space: normal;"> </span></p>
3.7.2參數為list示例的寫法
接口的方法聲明:
動態SQL語句:
- <!-- 7.2 foreach(循環List<String>參數) - 作為where中in的條件 -->
- <select id="getStudentListByClassIds_foreach_list" resultMap="resultMap_studentEntity">
- SELECT ST.STUDENT_ID,
- ST.STUDENT_NAME,
- ST.STUDENT_SEX,
- ST.STUDENT_BIRTHDAY,
- ST.STUDENT_PHOTO,
- ST.CLASS_ID,
- ST.PLACE_ID
- FROM STUDENT_TBL ST
- WHERE ST.CLASS_ID IN
- <foreach collection="list" item="classIdList" open="(" separator="," close=")">
- #{classIdList}
- </foreach>
- </select>
測試代碼,查詢學生中,在20000001、20000002這兩個班級的學生:
- @Test
- public void test7_2_foreach() {
- ArrayList<String> classIdList = new ArrayList<String>();
- classIdList.add("20000001");
- classIdList.add("20000002");
- List<StudentEntity> list = this.dynamicSqlMapper.getStudentListByClassIds_foreach_list(classIdList);
- for (StudentEntity e : list) {
- System.out.println(e.toString());
- }
- }
四、MyBatis主配置文件
在定義sqlSessionFactory時需要指定MyBatis主配置文件:
- <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
- <property name="configLocation" value="classpath:mybatis-config.xml" />
- <property name="dataSource" ref="dataSource" />
- </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文件中相應屬性值。
- <!-- 屬性替換 -->
- <properties resource="mysql.properties">
- <property name="jdbc.driverClassName" value="com.mysql.jdbc.Driver"/>
- <property name="jdbc.url" value="jdbc:mysql://localhost:3306/student_manager"/>
- <property name="username" value="root"/>
- <property name="password" value="limingnihao"/>
- </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) |
例如:
- <settings>
- <setting name="cacheEnabled" value="true" />
- <setting name="lazyLoadingEnabled" value="true" />
- <setting name="multipleResultSetsEnabled" value="true" />
- <setting name="useColumnLabel" value="true" />
- <setting name="useGeneratedKeys" value="false" />
- <setting name="enhancementEnabled" value="false" />
- <setting name="defaultExecutorType" value="SIMPLE" />
- </settings>
4.3 typeAliases類型別名
類型別名是Java 類型的簡稱。
它僅僅只是關聯到XML 配置,簡寫冗長的JAVA 類名。例如:
- <typeAliases>
- <typeAlias alias="UserEntity" type="com.manager.data.model.UserEntity" />
- <typeAlias alias="StudentEntity" type="com.manager.data.model.StudentEntity" />
- <typeAlias alias="ClassEntity" type="com.manager.data.model.ClassEntity" />
- </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直到語句被執行都不知道數據類型的這個現實導致的。
- public class LimingStringTypeHandler implements TypeHandler {
- @Override
- public void setParameter(PreparedStatement ps, int i, Object parameter, JdbcType jdbcType) throws SQLException {
- System.out.println("setParameter - parameter: " + ((String) parameter) + ", jdbcType: " + jdbcType.TYPE_CODE);
- ps.setString(i, ((String) parameter));
- }
- @Override
- public Object getResult(ResultSet rs, String columnName) throws SQLException {
- System.out.println("getResult - columnName: " + columnName);
- return rs.getString(columnName);
- }
- @Override
- public Object getResult(CallableStatement cs, int columnIndex) throws SQLException {
- System.out.println("getResult - columnIndex: " + columnIndex);
- return cs.getString(columnIndex);
- }
- }
在配置文件的typeHandlers中添加typeHandler標簽。
- <typeHandlers>
- <typeHandler javaType="String" jdbcType="VARCHAR" handler="liming.student.manager.type.LimingStringTypeHandler"/>
- </typeHandlers>
4.5 ObjectFactory對象工廠
每次MyBatis 為結果對象創建一個新實例,都會用到ObjectFactory。默認的ObjectFactory 與使用目標類的構造函數創建一個實例毫無區別,如果有已經映射的參數,那也可能使用帶參數的構造函數。
如果你重寫ObjectFactory 的默認操作,你可以通過繼承org.apache.ibatis.reflection.factory.DefaultObjectFactory創建一下你自己的。
ObjectFactory接口很簡單。它包含兩個創建用的方法,一個是處理默認構造方法的,另外一個是處理帶參數構造方法的。最終,setProperties方法可以被用來配置ObjectFactory。在初始化你的ObjectFactory實例后,objectFactory元素體中定義的屬性會被傳遞給setProperties方法。
- public class LimingObjectFactory extends DefaultObjectFactory {
- private static final long serialVersionUID = -399284318168302833L;
- @Override
- public Object create(Class type) {
- return super.create(type);
- }
- @Override
- public Object create(Class type, List<Class> constructorArgTypes, List<Object> constructorArgs) {
- System.out.println("create - type: " + type.toString());
- return super.create(type, constructorArgTypes, constructorArgs);
- }
- @Override
- public void setProperties(Properties properties) {
- System.out.println("setProperties - properties: " + properties.toString() + ", someProperty: " + properties.getProperty("someProperty"));
- super.setProperties(properties);
- }
- }
配置文件中添加objectFactory標簽
- <objectFactory type="liming.student.manager.configuration.LimingObjectFactory">
- <property name="someProperty" value="100"/>
- </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 引用。
例如: