MyBatis 是支持普通 SQL 查詢,存儲過程和高級映射的優秀持久層框架。 MyBatis 消除了幾乎所有的 JDBC 代碼和參數的手工設置以及對結果集的檢索。MyBatis 可以使用簡單的XML 或注解用於配置和原始映射,將接口和 Java 的 POJO(Plain Old Java Objects,普通的Java對象)映射成數據庫中的記錄。
MyBatis下載:https://github.com/mybatis/mybatis-3/releases
Mybatis實例
對一個User表的CRUD操作:
User表:
-- ---------------------------- -- Table structure for `user` -- ---------------------------- DROP TABLE IF EXISTS `user`; CREATE TABLE `user` ( `id` int(11) NOT NULL AUTO_INCREMENT, `userName` varchar(50) DEFAULT NULL, `userAge` int(11) DEFAULT NULL, `userAddress` varchar(200) DEFAULT NULL, PRIMARY KEY (`id`) ) ENGINE=InnoDB AUTO_INCREMENT=6 DEFAULT CHARSET=utf8; -- ---------------------------- -- Records of user -- ---------------------------- INSERT INTO `user` VALUES ('1', 'summer', '30', 'shanghai'); INSERT INTO `user` VALUES ('2', 'test2', '22', 'suzhou'); INSERT INTO `user` VALUES ('3', 'test1', '29', 'some place'); INSERT INTO `user` VALUES ('4', 'lu', '28', 'some place'); INSERT INTO `user` VALUES ('5', 'xiaoxun', '27', 'nanjing');
在Src目錄下建一個mybatis的xml配置文件Configuration.xml
<?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> <!-- mybatis別名定義 --> <typeAliases> <typeAlias alias="User" type="com.mybatis.test.User"/> </typeAliases> <environments default="development"> <environment id="development"> <transactionManager type="JDBC"/> <dataSource type="POOLED"> <property name="driver" value="com.mysql.jdbc.Driver"/> <property name="url" value="jdbc:mysql://127.0.0.1:3306/mybatis" /> <property name="username" value="root"/> <property name="password" value="admin"/> </dataSource> </environment> </environments> <!-- mybatis的mapper文件,每個xml配置文件對應一個接口 --> <mappers> <mapper resource="com/mybatis/test/User.xml"/> </mappers> </configuration>
定義User mappers的User.xml配置文件
<?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.mybatis.test.IUserOperation"> <!-- select語句 --> <select id="selectUserByID" parameterType="int" resultType="User"> select * from `user` where user.id = #{id} </select> <!-- 定義的resultMap,可以解決類的屬性名和數據庫列名不一致的問題--> <!-- <resultMap type="User" id="userResultMap"> <id property="id" column="user_id" /> <result property="userName" column="user_userName" /> <result property="userAge" column="user_userAge" /> <result property="userAddress" column="user_userAddress" /> </resultMap> --> <!-- 返回list的select語句,注意 resultMap的值是指向前面定義好的 --> <!-- <select id="selectUsersByName" parameterType="string" resultMap="userResultMap"> select * from user where user.userName = #{userName} </select> --> <select id="selectUsersByName" parameterType="string" resultType="User"> select * from user where user.userName = #{userName} </select> <!--執行增加操作的SQL語句。id和parameterType分別與IUserOperation接口中的addUser方法的名字和參數類型一致。 useGeneratedKeys設置為"true"表明要MyBatis獲取由數據庫自動生成的主鍵;keyProperty="id"指定把獲取到的主鍵值注入到User的id屬性--> <insert id="addUser" parameterType="User" useGeneratedKeys="true" keyProperty="id"> insert into user(userName,userAge,userAddress) values(#{userName},#{userAge},#{userAddress}) </insert> <update id="updateUser" parameterType="User" > update user set userName=#{userName},userAge=#{userAge},userAddress=#{userAddress} where id=#{id} </update> <delete id="deleteUser" parameterType="int"> delete from user where id=#{id} </delete> </mapper>
配置文件實現了接口和SQL語句的映射關系。selectUsersByName采用了2種方式實現,注釋掉的也是一種實現,采用resultMap可以把屬性和數據庫列名映射關系定義好,property為類的屬性,column是表的列名,也可以是表列名的別名!
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 | 設置驅動器在拋出異常前等待回應的最長時間,默認為不設值,由驅動器自己決定 | 正整數 | 未設置 |
fetchSize | 設置一個值后,驅動器會在結果集數目達到此數值后,激發返回,默認為不設值,由驅動器自己決定 | 正整數 | 驅動器決定 |
statementType | statement,preparedstatement,callablestatement。預准備語句、可調用語句 | STATEMENT、PREPARED、CALLABLE | PREPARED |
resultSetType | forward_only、scroll_sensitive、scroll_insensitive 只轉發,滾動敏感,不區分大小寫的滾動 | FORWARD_ONLY、SCROLL_SENSITIVE、SCROLL_INSENSITIVE | 驅動器決定 |
useGeneratedKeys | 告訴MyBatis 使用JDBC 的getGeneratedKeys 方法來獲取數據庫自己生成的主鍵(MySQL、SQLSERVER 等關系型數據庫會有自動生成的字段)。默認:false | true/false | false |
keyProperty | 標識一個將要被MyBatis設置進getGeneratedKeys的key 所返回的值,或者為insert 語句使用一個selectKey子元素。 |
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>
- 1
<!-- 刪除學生 --> <delete id="deleteStudent" parameterType="StudentEntity"> DELETE FROM STUDENT_TBL WHERE STUDENT_ID = #{studentID} </delete>
<!-- 查詢學生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()); }
多參數的實現
如果想傳入多個參數,則需要在接口的參數上添加@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);
<!-- 查詢學生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>
https://www.cnblogs.com/luxiaoxun/p/4035040.html