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中。
- /* 建立數據庫 */
- 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>
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());
- }
- }
- }
更詳細的功能源代碼http://limingnihao.javaeye.com/admin/blogs/782190頁面最下面;
二、SQL語句映射文件(1)resultMap
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>
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其他基本數據庫表字段到實體類屬性的映射。
最簡單的例子:
- <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、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實體類型。
例如,一個班級對應一個班主任。
首先定義好班級中的班主任屬性:
- private TeacherEntity teacherEntity;
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實體類型。
例如,一個班級有多個學生。
首先定義班級中的學生列表屬性:
- private List<StudentEntity> studentList;
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文件部分內容中。
二、SQL語句映射文件(2)增刪改查、參數、緩存
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 |