MyBatis的概述及使用

1.框架的概述

什麼是框架,框架從何而來,爲什麼使用框架?

    框架:

    1.是一系列jar包,本質是對JDK功能的拓展

    2.框架是一組程序的集合,包含了一系列的最佳實踐,作用是解決某個領域的問題。

不同框架的目的是解決不用領域的問題!

---------------------------------

最佳實踐(Bast Propertice):實際上是無數程序員經歷過無數次嘗試之後,總結出來的處理特定問題的特定方法。

    如果把程序員的自由發揮看作是一種通往成功的途徑,最佳實踐就是其中最短路徑,能極大的解放生產力。

最佳實踐三要素:可讀性,可維護性,可拓展性。

簡單就是美:消除重複  化繁爲簡  簡單必須可讀,簡單必須刻拓展  減少依賴,消除耦合

------------------------------------

WEB開發中的最佳實踐:分層開發模式(技術層面的“分而治之”)

JAVAEE開發根據職責的縱向劃分:變現層,業務層,持久層:

表現層:(Predentaion Layer):web/mvc負責處理與節目交互的相關操作(Struts2)

業務層:(Business Layer):service:負責複雜的業務邏輯計算和判斷(Spring)

持久層:(Persistent Layer):dao:負責將業務邏輯數據進行持久化儲存(Hibernate/MyBatis)

2 ORM思想和MyBatis框架概述

ORM對象關係映射(Object Relation Mapping 簡稱ORM/OR Mapping)

是一種爲了解決面向對象與關係數據庫存在的互不匹配的現象技術,簡單的說,ORM是通過使用描述對象和數據庫之間映射的元數據,將java程序中的對象自動持久化到關係數據庫中,避免直接使用SQL語句對關係型數據庫中的數據進行操作,減少代碼編寫量,提高產品質量。
ORM主要解決對象-關係的映射:

面向對象概念:面向關係概念
--------------------------
類               表
對象          表的行(記錄)
屬性          表的列(字段)

ORM的實現思想:

    將關係數據庫中表中的記錄映射爲對象,以對象的形式展現,程序員可以把對數據的操作轉化爲對對象的操作,因此ORM的目的是爲了方便開發人員以面向對象的思想來實現對數據庫的操作。

ORM 採用元數據來描述對象-關係映射細節

    元數據通常採用XML格式,並且放在專門的對象-關係映射文件中。

目前流行的ORM框架:

    1.JPA:本身是一種ORM規範,不是ORM框架,由各大ORM框架提供實現

    2.Hibernate:目前最流行的ORM框架,設計靈巧,性能優秀,文檔豐富

    3.MyBatis:本是apache的一個開源項目IBatis,提供的持久層框架包括SQL Maps和DAO,允許開發人員直接編寫SQL等

MyBatis前世今生:

    MyBatis 本是Apache的一個開源項目IBatis,2010年這個項目有Apache sofware foundation 遷移到了Google code,並且改名爲MyBatis,2013年11月遷移到Github。

IBatis一詞源於"internet abatis"的組合,是一個基於java的持久層框架。
ibatis提供的持久層框架包括SQL MAPS 和 Access Object Dao.

MyBatis的優勢:

    Mybatis  是支持普通SQL查詢,存儲過程和高級映射的優秀持久層框架。

    Mybatis  消除了幾乎所有的JDBC代碼和參數的手工設置以及結果的檢索。

    Mybatis  使用簡單的XML或註解用於配置和映射,將接口和java的POJOS(Plain Old Object,普通的java對象)映射成數據庫中的記錄。![ORM思維圖](https://img-blog.csdn.net/20180101211938063?watermark/2/text/aHR0cDovL2Jsb2cuY3Nkbi5uZXQvd2VpeGluXzQwMTYxNzA4/font/5a6L5L2T/fontsize/400/fill/I0JBQkFCMA==/dissolve/70/gravity/SouthEast)

3 準備工作

1.提供Product對象,IProductDAO,ProductDAOImpl(未實現),ProductDAOTest.
2.使用框架第一步:拷貝jar包。
    ①:MySQL驅動:mysql-connector-java-5.1.22-bin.jar
    ②:MyBatis的核心jar:mybatis-3.2.1.jar
    ③:MyBatis的依賴jar:MyBatis目錄/lib中所有的jar.
       PS:commons-longging-1.1.1.jar其實可以不需要
       記得看文檔來找答案:不丟人!
-----------------------------------------------------

MyBatis的主配置文件:

放在resources中的MyBatis-config.xml文件

在文檔中找的,不過我已經填好了,文檔就在MyBatis驅動包中的mybatis-3.4.1.pdf文檔
<?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">
            <!-- 事務管理器:JDBC的管理機制 -->
            <transactionManager type="JDBC" />
            <!-- 配置連接池(數據源) -->
            <dataSource type="POOLED">
                <property name="driver" value="com.mysql.jdbc.Driver" />
                <property name="url" value="jdbc:mysql://localhost:3306/jdbcdemo?useSSL=false" />
                <property name="username" value="root" />
                <property name="password" value="111111" />
            </dataSource>
        </environment>
    </environments>
    <!-- 關聯映射文件 -->
    <mappers>
        <mapper resource="cn\itsource\shopping\domain\ProductMapper.xml" />
    </mappers>
</configuration>

XML映射文件對SqlSession對象的調用

<?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">
 <!-- 映射Product對象和對應表關係的,操作該表/對象的SQL全部都寫在這裏 -->
<mapper namespace="cn.itsource.shopping.mapper.ProductMapper">
    <!-- 裏面寫SQL -->
    <!-- 
        id:唯一的標識,和namespace組成全局的唯一名稱
        cn.itsource.shopping.mapper.ProductMapper.list
        parameterType:方法的參數類型
        resultType:返回類型,表中一行記錄對應的對象
     -->

    <!-- 查詢所有 -->
    <select id="list" resultType="cn.itsource.shopping.domain.Product">
        SELECT * FROM product
    </select>

    <!-- 查詢單個 -->
    <select id="get" parameterType="long" resultType="cn.itsource.shopping.domain.Product">
        SELECT * FROM product where id = #{id}
    </select>

    <!-- 插入操作  -->
    <insert id="save" parameterType="cn.itsource.shopping.domain.Product">
        insert into product (productName,brand,supplier,salePrice,costPrice,cutoff,dir_id)
        values(#{productName},#{brand},#{supplier},#{salePrice},#{costPrice},#{cutoff},#{dir_id})
    </insert>

    <update id="update" parameterType="cn.itsource.shopping.domain.Product">
        UPDATE product SET productName = #{productName},brand = #{brand},supplier = #{supplier},
        salePrice = #{salePrice},costPrice = #{costPrice},cutoff = #{cutoff},dir_id = #{dir_id}
        WHERE id = #{id}
    </update>

    <delete id="delete" parameterType="long">
        delete from product where id = #{id}
    </delete>

</mapper>

日誌文件的配置

Log4簡介:

Log4j有三個主要組件:Loggers(記錄器),Appenders(輸出源)和Layouts(佈局)。
            課簡單理解爲日誌類別,日誌要輸出的地方和日誌以何種形式輸出,綜合使用這三個組件可以輕鬆的
            記錄信息的類型和級別,並可以在運行時控制日誌輸出的樣式和位置

log4j.rootLogger=ERROR, stdout

log4j.logger.cn.itsource.shopping=TRACE

log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%d %p [%c] - %m%n

4 操作步驟

無論是用過的Hibernate,MyBatis,操作步驟:

1.從配置文件(通常是XML配置文件中)得到sessionfactory(相當於DataSource)。

2.由sessionfactory  產生 session(相當於Connection,和Web中HttpSession無關)。

3.在session中完成對數據的增刪改查和事務提交等。

4.用完之後關閉session。
//1.加載MyBatis-connfig.xml 獲取SqlSessionFactory:DataSource
//2.使用SqlSessionFactory創建SqlSession對象:connection
//3.使用SqlSession完成CRUD,事務操作
//4.釋放SqlSession
public class ProductDAOImpl implements IProductDAO {

    public void save(Product pro) {
        try {
            SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder()
                    .build(Resources.getResourceAsReader("MyBatis-config.xml"));
            SqlSession sqlSession = sqlSessionFactory.openSession();
            sqlSession.insert("cn.itsource.shopping.mapper.ProductMapper.save", pro);//切記此處的""裏面只能寫cn.itsource.shopping.mapper.ProductMapper.詞
            sqlSession.commit();
            sqlSession.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void delete(Long id) {
        try {
            SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder()
                    .build(Resources.getResourceAsStream("MyBatis-config.xml"));
            SqlSession sqlSession = sqlSessionFactory.openSession();
            sqlSession.update("cn.itsource.shopping.mapper.ProductMapper.delete", id);
            sqlSession.commit();
            sqlSession.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void update(Product pro) {
        try {
            SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder()
                    .build(Resources.getResourceAsStream("MyBatis-config.xml"));
            SqlSession sqlSession = sqlSessionFactory.openSession();
            sqlSession.update("cn.itsource.shopping.mapper.ProductMapper.update", pro);
            sqlSession.commit();
            sqlSession.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public Product get(Long id) {
        try {
            InputStream config = Resources.getResourceAsStream("MyBatis-config.xml");
            SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(config);
            SqlSession sqlSession = sqlSessionFactory.openSession();
            Product obj = sqlSession.selectOne("cn.itsource.shopping.mapper.ProductMapper.get", id);
            sqlSession.close();
            return obj;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    public List<Product> list() {
        try {
            InputStream config = Resources.getResourceAsStream("MyBatis-config.xml");
            SqlSessionFactory sessionFactory = new SqlSessionFactoryBuilder().build(config);
            SqlSession session = sessionFactory.openSession();
            //namespace + id -->指定了唯一的一個SQL
            List<Product> list = session.selectList("cn.itsource.shopping.mapper.ProductMapper.list");
            session.close();
            return list;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

實現接口:

import java.util.List;

import cn.itsource.shopping.domain.Product;

public interface IProductDAO {
    void save(Product pro);

    void delete(Long id);

    void update(Product pro);//long id 包裝進去product

    Product get(Long id);

    List<Product> list();

}

測試類

public class ProductDAOTest {

    private IProductDAO dao = new ProductDAOImpl();

    @Test
    public void testSave() {
        Product pro = new Product();
        pro.setProductName("iphone9s");
        pro.setBrand("apple");
        pro.setSupplier("蘋果公司");
        pro.setSalePrice(new BigDecimal("7000"));
        pro.setCostPrice(new BigDecimal("2000"));
        pro.setCutoff(0.9);
        pro.setDir_id(3L);
        //pro.setId(12L);
        dao.save(pro);
    }

    @Test
    public void testDelete() {
        dao.delete(13L);
    }

    @Test
    public void testUpdate() {
        Product pro = new Product();
        pro.setProductName("iphone5s");
        pro.setBrand("apple9s");
        pro.setSupplier("蘋果公司2");
        pro.setSalePrice(new BigDecimal("6000"));
        pro.setCostPrice(new BigDecimal("1000"));
        pro.setCutoff(0.8);
        pro.setDir_id(5L);
        pro.setId(22L);
        dao.update(pro);
    }

    @Test
    public void testGet() {
        Product pro = dao.get(6L);
        System.out.println(pro);
    }

    @Test
    public void testList() {
        List<Product> list = dao.list();
        for (Product p : list) {
            System.out.println(p);
        }
    }

商品類對象

public class Product {
    private Long id;
    private String productName;
    private String brand;
    private String supplier;
    private BigDecimal salePrice;
    private BigDecimal costPrice;
    private Double cutoff;
    private Long dir_id;//分類編號

    public Long getId() {
        return id;
    }
    public String getProductName() {
        return productName;
    }
    public String getBrand() {
        return brand;
    }
    public String getSupplier() {
        return supplier;
    }
    public BigDecimal getSalePrice() {
        return salePrice;
    }
    public BigDecimal getCostPrice() {
        return costPrice;
    }
    public Double getCutoff() {
        return cutoff;
    }
    public Long getDir_id() {
        return dir_id;
    }
    public void setId(Long id) {
        this.id = id;
    }
    public void setProductName(String productName) {
        this.productName = productName;
    }
    public void setBrand(String brand) {
        this.brand = brand;
    }
    public void setSupplier(String supplier) {
        this.supplier = supplier;
    }
    public void setSalePrice(BigDecimal salePrice) {
        this.salePrice = salePrice;
    }
    public void setCostPrice(BigDecimal costPrice) {
        this.costPrice = costPrice;
    }
    public void setCutoff(Double cutoff) {
        this.cutoff = cutoff;
    }
    public void setDir_id(Long dir_id) {
        this.dir_id = dir_id;
    }
    public String toString() {
        return "Product [id=" + id + ", productName=" + productName + ", brand=" + brand + ", suppliet=" + supplier
                + ", salePrice=" + salePrice + ", costPrice=" + costPrice + ", cutoff=" + cutoff + ", dir_id=" + dir_id
                + "]";
    }
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章