MyBatis(1)——快速入門

MyBatis 簡介

MyBatis 本是apache的一個開源項目iBatis, 2010年這個項目由apache software foundation 遷移到了google code,而且更名爲MyBatis,是一個基於Java的持久層框架。html

  • 持久層: 能夠將業務數據存儲到磁盤,具有長期存儲能力,只要磁盤不損壞,在斷電或者其餘狀況下,從新開啓系統仍然能夠讀取到這些數據。
  • 優勢: 能夠使用巨大的磁盤空間存儲至關量的數據,而且很廉價
  • 缺點:慢(相對於內存而言)

爲何使用 MyBatis

在咱們傳統的 JDBC 中,咱們除了須要本身提供 SQL 外,還必須操做 Connection、Statment、ResultSet,不只如此,爲了訪問不一樣的表,不一樣字段的數據,咱們須要些不少雷同模板化的代碼,閒的繁瑣又枯燥java

而咱們在使用了 MyBatis 以後,只須要提供 SQL 語句就行了,其他的諸如:創建鏈接、操做 Statment、ResultSet,處理 JDBC 相關異常等等均可以交給 MyBatis 去處理,咱們的關注點因而能夠就此集中在 SQL 語句上,關注在增刪改查這些操做層面上。mysql

而且 MyBatis 支持使用簡單的 XML 或註解來配置和映射原生信息,將接口和 Java 的 POJOs(Plain Old Java Objects,普通的 Java對象)映射成數據庫中的記錄。git


搭建 MyBatis 環境

首先,咱們須要先下載和搭建 MyBatis 的開發環境。github

下載 MyBatis 工程包

打開連接 http://github.com/mybatis/mybatis-3/releases 下載 MyBatis 所須要的包和源碼,當前最新版本爲 3.4.6,官方還提供了文檔: 戳這裏,雖然感受寫得通常,但仍是有一些參考價值...唉,別當教程看,當字典看!web

下載好 MyBatis 的包解壓後,能夠獲得如下的文件目錄:sql

其中 mybatis-3.4.6.jar 包就是 MyBatis 的項目工程包,【lib】文件夾下就是 MyBatis 項目須要依賴的第三方包,pdf 文件是它英文版的說明,不要英文也能夠戳上面的連接。數據庫

爲 IDEA 配置 MyBatis 環境

IDEA 默認是不支持 MyBatis 開發的,須要本身下載第三方插件來支持,惋惜的是功能強大的【MyBatis Plugin】是收費的,須要咱們本身破解!apache

第一步:在 IDEA 中下載 MyBatis Plugin

在【File】菜單下找到【Settings】,而後再【Plugins】下點擊【Browse repositories..】:編程

在搜索欄中輸入【MyBatis Plugin】,而後點擊【Install】(我這裏是安裝好了因此沒有這個按鈕):

第二步:破解

有幸找到最新的破解方法,最新支持破解的版本號爲:v3.58 crack,下載連接:戳這裏

把它下載到 【D:\Download】目錄下,打開 idea.vmoptions (【Help】-> 【Eidt Custom VM Options...】):
在下方插入 -javaagent:D:/Download/ideaagent-1.2.jar

重啓 IDEA,首次啓動須要信任本地服務器 ssl 證書,點擊接受後如未激活,再次重啓便可:

至此,咱們就爲 IDEA 配置好了 MyBatis 的開發環境,能夠檢驗一下是否安裝成功:


第一個 MyBatis 程序

咱們來實際開發一個 MyBatis 程序,感覺一下。

第一步:準備數據庫

首先咱們建立一個數據庫【mybatis】,編碼方式設置爲 UTF-8,而後再建立一個名爲【student】的表,插入幾行數據:

DROP DATABASE IF EXISTS mybatis;
CREATE DATABASE mybatis DEFAULT CHARACTER SET utf8;

use mybatis;
CREATE TABLE student(
  id int(11) NOT NULL AUTO_INCREMENT,
  studentID int(11) NOT NULL UNIQUE,
  name varchar(255) NOT NULL,
  PRIMARY KEY (id)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

INSERT INTO student VALUES(1,1,'我沒有三顆心臟');
INSERT INTO student VALUES(2,2,'我沒有三顆心臟');
INSERT INTO student VALUES(3,3,'我沒有三顆心臟');

第二步:建立工程

在 IDEA 中新建一個 Java 工程,並命名爲【HelloMybatis】,而後導入必要的 jar 包:

  • mybatis-3.4.6.jar
  • mysql-connector-java-5.1.21-bin.jar

第三步:建立實體類

在 Package【pojo】下新建實體類【Student】,用於映射表 student:

package pojo;

public class Student {

    int id;
    int studentID;
    String name;

    /* getter and setter */
}

第四步:配置文件 mybatis-config.xml

在【src】目錄下建立 MyBaits 的主配置文件 mybatis-config.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>

    <!-- 別名 -->
    <typeAliases>
        <package name="pojo"/>
    </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://localhost:3306/mybatis?characterEncoding=UTF-8"/>
                <property name="username" value="root"/>
                <property name="password" value="root"/>
            </dataSource>
        </environment>
    </environments>
    <!-- 映射文件 -->
    <mappers>
        <mapper resource="pojo/Student.xml"/>
    </mappers>

</configuration>

第五步:配置文件 Student.xml

在 Package【pojo】下新建一個【Student.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="pojo">
    <select id="listStudent" resultType="Student">
        select * from  student
    </select>
</mapper>
  • 因爲上面配置了 <typeAliases> 別名,因此在這裏的 resultType 能夠直接寫 Student,而不用寫類的全限定名 pojo.Student
  • namespace 屬性其實就是對 SQL 進行分類管理,實現不一樣業務的 SQL 隔離
  • SQL 語句的增刪改查對應的標籤有:

第六步:編寫測試類

在 Package【test】小建立測試類【TestMyBatis】:

package test;

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 pojo.Student;

import java.io.IOException;
import java.io.InputStream;
import java.util.List;

public class TestMyBatis {

    public static void main(String[] args) throws IOException {
        // 根據 mybatis-config.xml 配置的信息獲得 sqlSessionFactory
        String resource = "mybatis-config.xml";
        InputStream inputStream = Resources.getResourceAsStream(resource);
        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
        // 而後根據 sqlSessionFactory 獲得 session
        SqlSession session = sqlSessionFactory.openSession();
        // 最後經過 session 的 selectList() 方法調用 sql 語句 listStudent
        List<Student> listStudent = session.selectList("listStudent");
        for (Student student : listStudent) {
            System.out.println("ID:" + student.getId() + ",NAME:" + student.getName());
        }

    }
}

運行測試類:

基本原理

  • 應用程序找 MyBatis 要數據
  • MyBatis 從數據庫中找來數據
    1.經過 mybatis-config.xml 定位哪一個數據庫
    2.經過 Student.xml 執行對應的 sql 語句
    3.基於 Student.xml 把返回的數據庫封裝在 Student 對象中
    4.把多個 Student 對象裝載一個 Student 集合中
  • 返回一個 Student 集合

參考資料:How2j.cn-MyBatis 相關教程


CRUD 操做

咱們來看看常規的一套增刪改查應該怎麼實現:

第一步:配置 Student.xml

首先,咱們在 SQL 映射文件中新增語句,用來支撐 CRUD 的系列操做

<?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="pojo">
    <select id="listStudent" resultType="Student">
        select * from  student
    </select>

    <insert id="addStudent" parameterType="Student">
        insert into student (id, studentID, name) values (#{id},#{studentID},#{name})
    </insert>

    <delete id="deleteStudent" parameterType="Student">
        delete from student where id = #{id}
    </delete>

    <select id="getStudent" parameterType="_int" resultType="Student">
        select * from student where id= #{id}
    </select>

    <update id="updateStudent" parameterType="Student">
        update student set name=#{name} where id=#{id}
    </update>
</mapper>
  • parameterType:要求輸入參數的類型
  • resultType:輸出的類型

第二步:實現增刪改查

package test;

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 pojo.Student;

import java.io.IOException;
import java.io.InputStream;
import java.util.List;

public class TestMyBatis {

    public static void main(String[] args) throws IOException {
        // 根據 mybatis-config.xml 配置的信息獲得 sqlSessionFactory
        String resource = "mybatis-config.xml";
        InputStream inputStream = Resources.getResourceAsStream(resource);
        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
        // 而後根據 sqlSessionFactory 獲得 session
        SqlSession session = sqlSessionFactory.openSession();

        // 增長學生
        Student student1 = new Student();
        student1.setId(4);
        student1.setStudentID(4);
        student1.setName("新增長的學生");
        session.insert("addStudent", student1);

        // 刪除學生
        Student student2 = new Student();
        student2.setId(1);
        session.delete("deleteStudent", student2);

        // 獲取學生
        Student student3 = session.selectOne("getStudent", 2);

        // 修改學生
        student3.setName("修改的學生");
        session.update("updateStudent", student3);

        // 最後經過 session 的 selectList() 方法調用 sql 語句 listStudent
        List<Student> listStudent = session.selectList("listStudent");
        for (Student student : listStudent) {
            System.out.println("ID:" + student.getId() + ",NAME:" + student.getName());
        }

        // 提交修改
        session.commit();
        // 關閉 session
        session.close();
    }
}

上述的程序中:

  • 經過 session.insert("addStudent", student1); 增長了一個 ID 和 studentID 都爲 4,名字爲「新增長的學生」 的學生
  • 經過 session.delete("deleteStudent", student2); 刪除了 ID = 1 的學生
  • 經過 Student student3 = session.selectOne("getStudent", 2); 獲取了 ID = 2的學生
  • 經過 session.update("updateStudent", student3); 將 ID = 2 的學生的名字修改成 「修改的學生」
  • 經過 session.commit() 來提交事務,也能夠簡單理解爲更新到數據庫

運行得到正確結果:

模糊查詢

若是要對數據庫中的 student 表進行模糊查詢,須要經過匹配名字中的某個字來查詢該用戶。

咱們首先在 Student.xml 配置文件中配置 SQL 映射:

<select id="findStudentByName" parameterMap="java.lang.String" resultType="Student">
    SELECT * FROM student WHERE name LIKE '%${value}%' 
</select>
  • 注意: <select> 標籤對中 SQL 語句的 「${}」 符號,表示拼接 SQL 串,將接受的參數內容不加任何修飾地拼接在 SQL 中,在 「${}」 中只能使用 value 來表明其中的參數。

由於是模糊查詢,因此獲得的查詢結果可能不止一個,因此咱們使用 SqlSession 的 selectList() 方法,寫一個測試方法:

@Test
public void test() throws IOException {

    // 根據 mybatis-config.xml 配置的信息獲得 sqlSessionFactory
    String resource = "mybatis-config.xml";
    InputStream inputStream = Resources.getResourceAsStream(resource);
    SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
    // 而後根據 sqlSessionFactory 獲得 session
    SqlSession session = sqlSessionFactory.openSession();

    // 模糊查詢
    List<Student> students = session.selectList("findStudentByName", "三顆心臟");
    for (Student student : students) {
        System.out.println("ID:" + student.getId() + ",NAME:" + student.getName());
    }
}

測試結果:

總結一下

  • 關於 parameterType: 就是用來在 SQL 映射文件中指定輸入參數類型的,能夠指定爲基本數據類型(如 int、float 等)、包裝數據類型(如 String、Interger 等)以及用戶本身編寫的 JavaBean 封裝類
  • 關於 resultType: 在加載 SQL 配置,並綁定指定輸入參數和運行 SQL 以後,會獲得數據庫返回的響應結果,此時使用 resultType 就是用來指定數據庫返回的信息對應的 Java 的數據類型。
  • 關於 「#{}」 : 在傳統的 JDBC 的編程中,佔位符用 「?」 來表示,而後再加載 SQL 以前按照 「?」 的位置設置參數。而 「#{}」 在 MyBatis 中也表明一種佔位符,該符號接受輸入參數,在大括號中編寫參數名稱來接受對應參數。當 「#{}」 接受簡單類型時能夠用 value 或者其餘任意名稱來獲取。
  • 關於 「${}」 : 在 SQL 配置中,有時候須要拼接 SQL 語句(例如模糊查詢時),用 「#{}」 是沒法達到目的的。在 MyBatis 中,「${}」 表明一個 「拼接符號」 ,能夠在原有 SQL 語句上拼接新的符合 SQL 語法的語句。使用 「${}」 拼接符號拼接 SQL ,會引發 SQL 注入,因此通常不建議使用 「${}」。
  • MyBatis 使用場景: 經過上面的入門程序,不難看出在進行 MyBatis 開發時,咱們的大部分精力都放在了 SQL 映射文件上。 MyBatis 的特色就是以 SQL 語句爲核心的不徹底的 ORM(關係型映射)框架。與 Hibernate 相比,Hibernate 的學習成本比較高,而 SQL 語句並不須要開發人員完成,只須要調用相關 API 便可。這對於開發效率是一個優點,可是缺點是沒辦法對 SQL 語句進行優化和修改。而 MyBatis 雖然須要開發人員本身配置 SQL 語句,MyBatis 來實現映射關係,可是這樣的項目能夠適應常常變化的項目需求。因此使用 MyBatis 的場景是:對 SQL 優化要求比較高,或是項目需求或業務常常變更。

參考資料:

  • 《Java EE 互聯網輕量級框架整合開發》
  • 《Spring MVC + MyBatis開發從入門到項目實戰》
  • How2j-MyBatis 系列教程
  • 全能的百度和萬能的大腦

歡迎轉載,轉載請註明出處!
簡書ID:@我沒有三顆心臟
github:wmyskxz 歡迎關注公衆微信號:wmyskxz_javaweb 分享本身的Java Web學習之路以及各類Java學習資料

相關文章
相關標籤/搜索