mybatis 學習筆記(一):mybatis 初認識

來源:互聯網
上載者:User
mybatis 學習筆記(一):mybatis 初認識簡介

MyBatis是一個Java持久層架構,它通過XML描述符或註解把對象與預存程序或SQL語句關聯起來。mybatis 可以將 preparedStatement 中的輸入參數自動進行映射,將查詢結果集靈活映射成 java 對象。所以使用 mybatis 我們就可以不用寫原生 jdbc 程式,並且能很好的避免 原生 jdbc 中 SQL 注入的問題。

一個完整 mybatis 程式的操作過程

1 配置 mybatis 的全域設定檔 SqlMapConfig.xml(名稱不固定),該檔案配置了資料來源。事務等 mybatis 運行環境。

2 建立 java 檔案,封裝資料庫物件。

3 配置對應檔 mapper.xml(名稱不固定), 在該檔案中,我們將對資料庫封裝的對象進行 SQL 陳述式操作。並在全域設定檔中通過mapper載入該對應檔。

4 另外建立java 檔案,通過設定檔,載入 mybatis 運行環境,建立 SqlSessionFactory 會話工廠(SqlSessionFactory 在實際使用時按單例方式)。

5 通過 SqlSessionFactory 建立 SqlSessionSqlSession 是一個面向使用者介面(提供操作資料庫方法),實現對象是線程不安全的,建議sqlSession 應用場合在方法體內。

6 調用sqlSession的方法去操作資料。如果需要提交事務,需要執行SqlSessioncommit()方法。

7 釋放資源,關閉SqlSession

mybatis 執行個體

下面我們通過一個具體的例子來實現 mybatis 的查詢功能。

前提條件

首先是運行 mybatis 需要的前提條件,在這裡我們需要串連資料庫,所以需要 java 串連 MySQL 資料庫的 jar 包,其次還需要 mybatis 的核心包,如果還需要用到日誌功能的話還需要 log4j.jar 等,mybatis 的相關依賴可以在 GitHub 上找到:mybatis 地址

我們通過 maven 來匯入具體需要的 jar 包,maven 的 pom.xml 中配置如下:

<?xml version="1.0" encoding="UTF-8"?><project xmlns="http://maven.apache.org/POM/4.0.0"         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">    <modelVersion>4.0.0</modelVersion>    <groupId>cn.itcast</groupId>    <artifactId>mybatis</artifactId>    <version>1.0-SNAPSHOT</version>    <dependencies>        <!-- mysql 驅動 -->        <dependency>            <groupId>mysql</groupId>            <artifactId>mysql-connector-java</artifactId>            <version>8.0.12</version>        </dependency>        <!-- test 測試檔案 -->        <dependency>            <groupId>junit</groupId>            <artifactId>junit</artifactId>            <version>4.12</version>        </dependency>        <!-- mybatis 核心jar包 -->        <dependency>            <groupId>org.mybatis</groupId>            <artifactId>mybatis</artifactId>            <version>3.4.6</version>        </dependency>        <!-- mybatis 附加功能包,如日誌功能等 -->        <dependency>            <groupId>org.apache.ant</groupId>            <artifactId>ant</artifactId>            <version>1.9.6</version>        </dependency>        <dependency>            <groupId>org.apache.ant</groupId>            <artifactId>ant-launcher</artifactId>            <version>1.9.6</version>        </dependency>        <dependency>            <groupId>org.ow2.asm</groupId>            <artifactId>asm</artifactId>            <version>5.2</version>        </dependency>        <dependency>            <groupId>cglib</groupId>            <artifactId>cglib</artifactId>            <version>3.2.5</version>        </dependency>        <dependency>            <groupId>commons-logging</groupId>            <artifactId>commons-logging</artifactId>            <version>1.2</version>        </dependency>        <dependency>            <groupId>org.javassist</groupId>            <artifactId>javassist</artifactId>            <version>3.22.0-GA</version>        </dependency>        <dependency>            <groupId>log4j</groupId>            <artifactId>log4j</artifactId>            <version>1.2.17</version>        </dependency>        <dependency>            <groupId>org.apache.logging.log4j</groupId>            <artifactId>log4j-api</artifactId>            <version>2.3</version>        </dependency>        <dependency>            <groupId>org.apache.logging.log4j</groupId>            <artifactId>log4j-core</artifactId>            <version>2.3</version>        </dependency>        <dependency>            <groupId>ognl</groupId>            <artifactId>ognl</artifactId>            <version>3.1.16</version>        </dependency>        <dependency>            <groupId>org.slf4j</groupId>            <artifactId>slf4j-api</artifactId>            <version>1.7.25</version>        </dependency>        <dependency>            <groupId>org.slf4j</groupId>            <artifactId>slf4j-log4j12</artifactId>            <version>1.7.25</version>            <scope>test</scope>        </dependency>    </dependencies></project>
資料庫配置

建立 sample 資料庫,建立 user 表,添加 id,username,sex,birthday,address 五個欄位,添加記錄。

如下:

建立全域設定檔和記錄檔

在 resources 檔案夾下建立 SqlMapconfig.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>    <!-- 和spring整合後 environments配置將廢除-->    <environments default="development">        <environment id="development">            <!-- 使用jdbc交易管理,事務控制由mybatis-->            <transactionManager type="JDBC" />            <!-- 資料庫連接池,由mybatis管理-->            <dataSource type="POOLED">                <property name="driver" value="com.mysql.jdbc.Driver" />                <property name="url" value="jdbc:mysql:///sampledb" />                <property name="username" value="root" />                <property name="password" value="" />            </dataSource>        </environment>    </environments>    <!-- 載入對應檔 -->    <mappers>        <mapper resource="sqlmap/User.xml"/>    </mappers></configuration>

同樣的,在該檔案夾下建立 log4j.properties 記錄檔,設定為 DEBUG 模式:

# Global logging configuration#開發環境中使用 DEBUG 模式,上線後使用 INFO 或 ERROR 模式log4j.rootLogger=DEBUG, stdout# Console output...log4j.appender.stdout=org.apache.log4j.ConsoleAppenderlog4j.appender.stdout.layout=org.apache.log4j.PatternLayoutlog4j.appender.stdout.layout.ConversionPattern=%5p [%t] - %m%n
封裝資料庫物件,建立對應檔

建立 User.java ,封裝好資料庫物件:

package cn.itcast.mybatis.po;import java.util.Date;public class User {    //屬性名稱要和資料庫表的欄位對應    private int id;    private String username;// 使用者姓名    private String sex;// 性別    private Date birthday;// 生日    private String address;// 地址    public int getId() {        return id;    }    public void setId(int id) {        this.id = id;    }    public String getUsername() {        return username;    }    public void setUsername(String username) {        this.username = username;    }    public String getSex() {        return sex;    }    public void setSex(String sex) {        this.sex = sex;    }    public Date getBirthday() {        return birthday;    }    public void setBirthday(Date birthday) {        this.birthday = birthday;    }    public String getAddress() {        return address;    }    public void setAddress(String address) {        this.address = address;    }    @Override    public String toString() {        return "User{" +                "id=" + id +                ", username='" + username + '\'' +                ", sex='" + sex + '\'' +                ", birthday=" + birthday +                ", address='" + address + '\'' +                '}';    }}

建立對應檔 User.xml,執行 SQL 查詢操作:

<?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"><!-- namespace 命名空間,作用就是對sql進行分類化管理,理解為sql隔離 --><mapper namespace="test">    <!-- 通過select執行資料庫查詢     id:標識對應檔中的sql,稱為statement的id     將sql語句封裝到mappedStatement對象中,所以將id稱為statement的id     parameterType:指定輸入參數的類型     #{}標示一個預留位置     #{value}其中value表示接收輸入參數的名稱,如果輸入參數是簡單類型,那麼#{}中的值可以任意     resultType:指定sql輸出結果的映射的java物件類型,select指定resultType表示將單條記錄映射成java對象     -->    <select id="findUserById" parameterType="int" resultType="cn.itcast.mybatis.po.User">        SELECT * FROM USER WHERE id=#{value}    </select></mapper>
建立測試檔案,執行 SQL 操作

檔案目錄結構:

MybatisFirst.java:

package cn.itcast.mybatis.first;import cn.itcast.mybatis.po.User;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.Date;import java.util.List;public class MybatisFirst {    //根據 id 查詢使用者,得到一條記錄結果    @Test    public void findUserByIdTest() throws IOException {        //mybatis 設定檔        String resource = "SqlMapConfig.xml";        //得到設定檔流        InputStream inputStream = (InputStream) Resources.getResourceAsStream(resource);        //建立會話工廠        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);        //通過工廠得到 SqlSession        SqlSession sqlSession = sqlSessionFactory.openSession();        //通過 SqlSession 操作資料庫        //第一個參數:對應檔中 statement 的 id,等於=namespace+"."+statement 的id        //第二個參數:指定和對應檔中所匹配的 paramenterType 類型的對象        User user = sqlSession.selectOne("test.findUserById", 1);        System.out.println(user);        //釋放資源        sqlSession.close();    }}

運行 findUserByIdTest() 方法, 查詢 id 值為1的使用者資訊,可以看到控制台正確返回資訊:

至此,一個完整的 mybatis 程式關於查詢操作我們就實現出來了。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.