以下內容的公開課視頻已經錄製,需要的同學可留言
MyBatis
作爲一個應用廣泛的優秀的持久層ORM框架,已經成了JavaWeb世界近乎標配的部分,它支持定製化 SQL、存儲過程以及高級映射。MyBatis
避免了幾乎所有的 JDBC 代碼和手動設置參數以及獲取結果集。MyBatis
可以使用簡單的 XML 或註解來配置和映射原生類型、接口和 Java 的 POJO(Plain Old Java Objects,普通老式 Java 對象)爲數據庫中的記錄。
1. 下載源碼
下載最新的穩定版或者目前項目中使用的MyBatis
源代碼,本課以MyBatis
3.5.1爲例進行講解,(目前最新版本爲3.5.2-SNAPSHOT)。
下載地址: https://github.com/mybatis/mybatis-3
注意按照讀tag進行版本選擇。
2. 創建源碼項目工程
下載源碼後,在idea中導入pom工程,需要按照以下步驟進行修改調整,項目才能編譯成功。
- pom文件中
ognl
、javassist
修改爲<optional>false</optional>
<dependency>
<groupId>ognl</groupId>
<artifactId>ognl</artifactId>
<version>3.2.10</version>
<scope>compile</scope>
<optional>false</optional>
</dependency>
<dependency>
<groupId>org.javassist</groupId>
<artifactId>javassist</artifactId>
<version>3.24.1-GA</version>
<scope>compile</scope>
<optional>false</optional>
</dependency>
刪除項目目錄下的license.txt
如果不刪除的話,在執行maven install時會出錯。手動下載jar包到本地
這個視情況而定,如果本地執行maven install時出現如下錯誤
[INFO] --- maven-surefire-plugin:2.7.1:test (default-test) @ wms ---
[WARNING] Error injecting: org.apache.maven.plugin.surefire.SurefirePlugin
java.lang.NoClassDefFoundError: org/apache/maven/surefire/util/NestedCheckedException
at java.lang.ClassLoader.defineClass1(Native Method)
則可以考慮手動下載對應jar包到本地maven倉庫中。
-
關閉maven-pdf-plugin
<!-- <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-pdf-plugin</artifactId> </plugin> -->
-
關閉test
執行maven install 時忽略test。
-
執行maven install
將
MyBatis
編譯安裝到本地maven倉庫。
3. 搭建簡單demo
從最簡單的demo入手,前期先不要集成Spring,只看最簡單的最原始的MyBatis
,熟悉了MyBatis
源碼後再看如何與Spring集成;
結合官方文檔搭建demo:http://www.mybatis.org/mybatis-3/zh/getting-started.html
基本使用流程
-
引入依賴
<dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis</artifactId> <version>3.5.1</version> </dependency> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>5.1.46</version> </dependency> <dependency> <groupId>log4j</groupId> <artifactId>log4j</artifactId> <version>1.2.17</version> </dependency>
-
創建xml配置文件
mybatis-config.xml
<?xml version="1.0" encoding="utf-8" ?> <!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Cofig 3.0//EN" "http://mybatis.org/dtd/mybatis-3-config.dtd"> <configuration> <environments default="development"> <environment id="development"> <transactionManager type="JDBC"></transactionManager> <dataSource type="POOLED"> <property name="driver" value="com.mysql.jdbc.Driver"/> <property name="url" value="jdbc:mysql://localhost:3306/test"/> <property name="username" value="root"/> <property name="password" value="123456"/> </dataSource> </environment> </environments> <mappers> <mapper resource="EmployeeMapper.xml"></mapper> </mappers> </configuration>
EmployeeMapper.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.boxuegu.javaee.mybatissourcelearn.dao.EmployeeMapper"> <select id="getEmployeeById" resultType="com.boxuegu.javaee.mybatissourcelearn.dto.Employee"> select id,last_name lastname,gender, email from bxg_employee where id=#{id} </select> </mapper>
-
創建dto對象
Employee.java
package com.boxuegu.javaee.mybatissourcelearn.dto; /** * @author Jam Fang https://www.jianshu.com/u/0977ede560d4 * @version 創建時間:05.24 15:27 */ public class Employee { private Integer id; private String lastName; private String email; private String gender; @Override public String toString() { return "Employee{" + "id=" + id + ", lastName='" + lastName + '\'' + ", email='" + email + '\'' + ", gender='" + gender + '\'' + '}'; } public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getLastName() { return lastName; } public void setLastName(String lastName) { this.lastName = lastName; } public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } public String getGender() { return gender; } public void setGender(String gender) { this.gender = gender; } }
-
創建dao
EmployeeMapper.java
package com.boxuegu.javaee.mybatissourcelearn.dao; import com.boxuegu.javaee.mybatissourcelearn.dto.Employee; /** * @author Jam Fang https://www.jianshu.com/u/0977ede560d4 * @version 創建時間:05.24 17:32 */ public interface EmployeeMapper { public Employee getEmployeeById(Integer id); }
-
創建數據庫測試表
-- ---------------------------- -- Table structure for bxg_employee -- ---------------------------- DROP TABLE IF EXISTS `bxg_employee`; CREATE TABLE `bxg_employee` ( `id` int(11) NOT NULL AUTO_INCREMENT, `last_name` varchar(255) DEFAULT NULL, `gender` char(1) DEFAULT NULL, `email` varchar(255) DEFAULT NULL, PRIMARY KEY (`id`) ) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=utf8; -- ---------------------------- -- Records of bxg_employee -- ---------------------------- INSERT INTO `bxg_employee` VALUES ('1', 'zhangsan', '1', '[email protected]');
-
創建測試代碼
package com.boxuegu.javaee.mybatissourcelearn; import com.boxuegu.javaee.mybatissourcelearn.dao.EmployeeMapper; import com.boxuegu.javaee.mybatissourcelearn.dto.Employee; import org.apache.ibatis.io.Resources; import org.apache.ibatis.session.SqlSession; import org.apache.ibatis.session.SqlSessionFactory; import org.apache.ibatis.session.SqlSessionFactoryBuilder; import java.io.IOException; import java.io.InputStream; /** * @author Jam Fang https://www.jianshu.com/u/0977ede560d4 * @version 創建時間:2019/6/17 13:16 */ public class Test { public static void main(String[] args) { //1.加載配置文件 String resource = "mybatis-config.xml"; InputStream inputStream = null; try { inputStream = Resources.getResourceAsStream(resource); } catch (IOException e) { e.printStackTrace(); } //2. 獲取sqlSessionFactory SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream); //3. 獲取sqlSession SqlSession sqlSession = sqlSessionFactory.openSession(); try { //4. 獲取mapper接口實現 EmployeeMapper mapper = sqlSession.getMapper(EmployeeMapper.class); System.out.println("mapper::::" + mapper.getClass()); //5. 執行sql語句 Employee employee = mapper.getEmployeeById(1); System.out.println(employee); } finally { sqlSession.close(); } } }