1. 程式人生 > 實用技巧 >Mybatis框架的搭建步驟

Mybatis框架的搭建步驟

Mybatis框架的搭建步驟:

今日內容:

1、什麼是 MyBatis?

2、Mybatis框架的搭建步驟;

3、Mybatis框架搭建步驟注意事項。

執行環境:

  JDK8 + IntelliJ IDEA 2018.2.1

一、什麼是 MyBatis?

​ MyBatis 是一款優秀的持久層框架,它支援自定義 SQL、儲存過程以及高階對映。MyBatis 免除了幾乎所有的 JDBC 程式碼以及設定引數和獲取結果集的工作。MyBatis 可以通過簡單的 XML 或註解來配置和對映原始型別、介面和 Java POJO(Plain Old Java Objects,普通老式 Java 物件)為資料庫中的記錄。

二、Mybatis框架的搭建步驟:

1、新建一個java工程(day53):

2、載入包:

<dependencies>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.12</version>
        </dependency>
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.34</version>
        </dependency>
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis</artifactId>
            <version>3.5.6</version>
        </dependency>
    </dependencies>
    
    <!--
        idea掃描不到mapper層的BookMapper.xml檔案,在pom檔案中加入 如下程式碼即可
    
--> <build> <resources> <resource> <directory>${basedir}/src/main/java</directory> <includes> <include>**/*.xml</include> </includes> </resource> </resources> </build>

3、在resources包中寫核心配置檔案(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>
    <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/books"/>
                <property name="username" value="root"/>
                <property name="password" value=""/>
            </dataSource>
        </environment></environments>
    <mappers>
        <!--對映檔案 resource中放相對路徑-->
        <mapper resource="com/cyq/book/mapper/BookMapper.xml"/>
    </mappers>
</configuration>

4、建包建類:

​ ①:Book

package com.cyq.book.pojo;
​
import java.io.Serializable;
​
/**
 * @author cyq
 * @version 1.0
 */
​
@SuppressWarnings("unused")
public class Book implements Serializable {
    /**
     * 圖書主鍵
     */
    private Integer bookId;
    /**
     * 圖書名稱
     */
    private String bookName;
    /**
     * 圖書作者
     */
    private String bookAuthor;
    /**
     * 圖書標記 1:已借閱,0:未借閱
     */
    private Integer bookFlag;
    /**
     * 圖書編號
     */
    private String bookNumber;
    /**
     * 出版社名
     */
    private String bookPublish;
​
    public Book(Integer bookId, String bookName, String bookAuthor, Integer bookFlag, String bookNumber, String bookPublish) {
        this.bookId = bookId;
        this.bookName = bookName;
        this.bookAuthor = bookAuthor;
        this.bookFlag = bookFlag;
        this.bookNumber = bookNumber;
        this.bookPublish = bookPublish;
    }
​
    @Override
    public String toString() {
        return "Book{" +
                "bookId=" + bookId +
                ", bookName='" + bookName + '\'' +
                ", bookAuthor='" + bookAuthor + '\'' +
                ", bookFlag=" + bookFlag +
                ", bookNumber='" + bookNumber + '\'' +
                ", bookPublish='" + bookPublish + '\'' +
                '}';
    }
​
    public Integer getBookId() {
        return bookId;
    }
​
    public void setBookId(Integer bookId) {
        this.bookId = bookId;
    }
​
    public String getBookName() {
        return bookName;
    }
​
    public void setBookName(String bookName) {
        this.bookName = bookName;
    }
​
    public String getBookAuthor() {
        return bookAuthor;
    }
​
    public void setBookAuthor(String bookAuthor) {
        this.bookAuthor = bookAuthor;
    }
​
    public Integer getBookFlag() {
        return bookFlag;
    }
​
    public void setBookFlag(Integer bookFlag) {
        this.bookFlag = bookFlag;
    }
​
    public String getBookNumber() {
        return bookNumber;
    }
​
    public void setBookNumber(String bookNumber) {
        this.bookNumber = bookNumber;
    }
​
    public String getBookPublish() {
        return bookPublish;
    }
​
    public void setBookPublish(String bookPublish) {
        this.bookPublish = bookPublish;
    }
​
    public Book() {
    }
}

​ ②:BookMapper:(相當於dao類)

package com.cyq.book.mapper;
​
import com.cyq.book.pojo.Book;
​
import java.util.List;
​
public interface BookMapper {
    public List<Book> queryAllBook();
}

​ ③:BookMapper.xml:(相當於dao的實現類)

<?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.cyq.book.mapper.BookMapper">
    //id裡寫BookMapper裡對應的方法
    <select id="queryAllBook" resultType="com.cyq.book.pojo.Book">
        select * from booksinfo//sql語句
    </select>
</mapper>

5、寫測試類:

package com.cyq.book.test;
​
import com.cyq.book.mapper.BookMapper;
import com.cyq.book.pojo.Book;
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 org.junit.Test;
​
import java.io.IOException;
import java.io.InputStream;
import java.util.List;
​
public class BookMapperTest {
    /**
     * 測試類Dao層程式碼
     */
    @Test
    public void testBookMapper(){
        //宣告resource,代表mybatis框架的核心配置檔案
        String resource="mybatis-config.xml";
        InputStream inputStream =null;
        try {
            /**
             * 通過mybatis框架提供的Resources工具類能夠將resource引數,得到輸入流
             *  即可以獲得,mybatis-config.xml中的資訊,例如:
             *  driver,url,username,password
             */
            inputStream = Resources.getResourceAsStream(resource);
            //通過new SqlSessionFactoryBuilder().build(inputStream);
            //將mybatis-config.xml中的引數傳輸到了sqlSessionFactory
            //mybatis框架的核心是sqlSessionFactory
            SqlSessionFactory sqlSessionFactory  = new SqlSessionFactoryBuilder().build(inputStream);
            //SqlSession包含了資料庫操作的增傷改查,以及事務提交,以及connection的獲取
            //sqlSession是幫我們進行資料庫Dao層操作的最終物件
            SqlSession sqlSession = sqlSessionFactory.openSession();
            //進行查詢         sqlSession.封裝了getMapper方法,通過傳入介面類物件,從而能結合UserMapper.xml檔案,進行資料庫操作
            List<Book> bookList=sqlSession.getMapper(BookMapper.class).queryAllBook();
           //List<User> userList=sqlSession.selectList("com.cyq.book.mapper.BookMapper.queryAllBook");
            for (Book book:
                 bookList) {
                System.out.println(book);
            }
            //關閉sqlSession
            sqlSession.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

Mybatis框架搭建步驟注意事項:

  • Resources:建包,只能手動一個一個建;

  • dao層的介面名和對映檔案的名字必須一致,且對映檔案只能寫在resources目錄下

  • mapper對映檔案中的namespace只能和介面的類路徑保持一致

  • 在mybatis-config.xml中元素標籤的位置是有順序的,順序不對不能成功執行

  • 記得將mapper對映檔案引入到mybatis.xml檔案中去

  • 做sqlSession增刪改的時候記得sqlSession.commit();

  • 別名不區分大小寫,增刪改對映檔案中是沒有返回值型別的;int型別會預設返回.

執行效果圖:

今天的分享就到這裡,拜拜溜…