1. 程式人生 > >Mybatis入門最簡單例項

Mybatis入門最簡單例項

Mybatis入門例項

本文使用IDEA建立mybatis專案,併成功coding一個最簡單的mybatis示例
(本文參靠自以下文章,非常感謝原作者!)

MyBatis官方文件的一句話,道出了mybatis框架的核心要素

每個基於 MyBatis 的應用都是以一個 SqlSessionFactory 的例項為中心的。

所有程式碼都是圍繞SqlSessionFactory展開的。

接下來展示建立mybatis的步驟
一、在IDEA中建立一個maven專案。
在maven的pom.xml配置檔案中加入mybatis依賴、jdbc驅動如下

    <!-- mybatis核心包 -->
<dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis</artifactId> <version>3.3.0</version> </dependency> <!-- mysql驅動包 --> <dependency> <groupId>mysql</groupId> <artifactId
>
mysql-connector-java</artifactId> <version>5.1.29</version> </dependency>

二、為程式碼方便,還可以使用mybatis的generator外掛
繼續在pom中新增依賴

    <build>
        <finalName>xxx工程名</finalName>
        <plugins>
            <plugin>
                <groupId
>
org.mybatis.generator</groupId> <artifactId>mybatis-generator-maven-plugin</artifactId> <version>1.3.2</version> <configuration> <verbose>true</verbose> <overwrite>true</overwrite> </configuration> </plugin> </plugins> </build>

然後在resources資料夾下新增generatorConfig.xml的配置檔案

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE generatorConfiguration
        PUBLIC "-//mybatis.org//DTD MyBatis Generator Configuration 1.0//EN"
        "http://mybatis.org/dtd/mybatis-generator-config_1_0.dtd">

<generatorConfiguration>
    <!--匯入屬性配置-->
    <properties resource="datasource.properties"></properties>

    <!--指定特定資料庫的jdbc驅動jar包的位置-->
    <classPathEntry location="${db.driverLocation}"/>

    <context id="default" targetRuntime="MyBatis3">

        <!-- optional,旨在建立class時,對註釋進行控制 -->
        <commentGenerator>
            <property name="suppressDate" value="true"/>
            <property name="suppressAllComments" value="true"/>
        </commentGenerator>

        <!--jdbc的資料庫連線 -->
        <jdbcConnection
                driverClass="${db.driverClassName}"
                connectionURL="${db.url}"
                userId="${db.username}"
                password="${db.password}">
        </jdbcConnection>


        <!-- 非必需,型別處理器,在資料庫型別和java型別之間的轉換控制-->
        <javaTypeResolver>
            <property name="forceBigDecimals" value="false"/>
        </javaTypeResolver>


        <!-- Model模型生成器,用來生成含有主鍵key的類,記錄類 以及查詢Example類
            targetPackage     指定生成的model生成所在的包名
            targetProject     指定在該專案下所在的路徑
        -->
        <!--<javaModelGenerator targetPackage="com.mybatis.pojo" targetProject=".\src\main\java">-->
        <javaModelGenerator targetPackage="com.mybatis.pojo" targetProject="./src/main/java">
            <!-- 是否允許子包,即targetPackage.schemaName.tableName -->
            <property name="enableSubPackages" value="false"/>
            <!-- 是否對model新增 建構函式 -->
            <property name="constructorBased" value="true"/>
            <!-- 是否對類CHAR型別的列的資料進行trim操作 -->
            <property name="trimStrings" value="true"/>
            <!-- 建立的Model物件是否 不可改變  即生成的Model物件不會有 setter方法,只有構造方法 -->
            <property name="immutable" value="false"/>
        </javaModelGenerator>

        <!--mapper對映檔案生成所在的目錄 為每一個數據庫的表生成對應的SqlMap檔案 -->
        <!--<sqlMapGenerator targetPackage="mappers" targetProject=".\src\main\resources">-->
        <sqlMapGenerator targetPackage="mappers" targetProject="./src/main/resources">
            <property name="enableSubPackages" value="false"/>
        </sqlMapGenerator>

        <!-- 客戶端程式碼,生成易於使用的針對Model物件和XML配置檔案 的程式碼
                type="ANNOTATEDMAPPER",生成Java Model 和基於註解的Mapper物件
                type="MIXEDMAPPER",生成基於註解的Java Model 和相應的Mapper物件
                type="XMLMAPPER",生成SQLMap XML檔案和獨立的Mapper介面
        -->

        <!-- targetPackage:mapper介面dao生成的位置 -->
        <!--<javaClientGenerator type="XMLMAPPER" targetPackage="com.mmall.dao" targetProject=".\src\main\java">-->
        <javaClientGenerator type="XMLMAPPER" targetPackage="com.mybatis.dao" targetProject="./src/main/java">
            <!-- enableSubPackages:是否讓schema作為包的字尾 -->
            <property name="enableSubPackages" value="false" />
        </javaClientGenerator>

        <!-- 該處與資料庫中要生成的表相對應-->
        <table tableName="Student" domainObjectName="Student" enableCountByExample="false" enableUpdateByExample="false" enableDeleteByExample="false" enableSelectByExample="false" selectByExampleQueryId="false"></table>


        <!-- geelynote mybatis外掛的搭建 -->
    </context>
</generatorConfiguration>

然後在idea右側maven標籤中找到mybatis-generator,根據配置檔案中的相應配置來生成對應的bean類和mapper類

三、完成上述兩步環境搭建後,需要配置mybatis的配置檔案
在resources資料夾下,新建一個mybatis-config.xml的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/mybatis?characterEncoding=utf-8"/>
                <property name="username" value="root"/>
                <property name="password" value="root"/>
            </dataSource>
        </environment>
    </environments>
    <!-- 此處要載入所需要使用的mapper -->
    <mappers>
        <mapper resource="mappers/StudentMapper.xml"/>
    </mappers>
</configuration>

四、完成配置後,新建一個測試類,來測試mybatis的配置效果

public class StudentTest {

    public static void main (String[] args) throws IOException {
        String resource = "mybatis-config.xml";
        //1.載入MyBatis的配置檔案:mybati-config.xml(它也載入關聯的對映檔案,也就是mappers節點下的對映檔案)
        InputStream inputStream = Resources.getResourceAsStream(resource);
        //2.SqlSessionFactoryBuuilder例項通過輸入流呼叫build方法來建立sqlsession工廠
        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
        //3.通過工廠來獲取sqlsession的例項,sqlsession完全包含了面向資料庫執行sql命令所需的所有方法。
        SqlSession sqlSession = sqlSessionFactory.openSession();
        //4.準備基本資訊
        //4.1)statement:用來定位對映檔案(StudengtMapper.xml)中的語句(通過namespace id + select id) 下句中 com.mybatis.dao.StudentMapper為namespace id/selectByPrimaryKey為select id
        String statement = "com.mybatis.dao.StudentMapper.selectByPrimaryKey";
        //4.2)parameter:傳進去的引數,也就是需要獲取students表中主鍵值為1的記錄
        int parameter = 1;
        //5.sqlsession例項來直接執行已對映的sql語句,selectOne表示獲取的是一條記錄
        Student student = sqlSession.selectOne(statement,parameter);
        System.out.print(student.toString());
        //6.關閉輸入流和sqlsession例項
        inputStream.close();
        sqlSession.close();
    }
}

為體現介面式程式設計的思想,可將上述部分程式碼替換為

        StudentMapper mapper = sqlSession.getMapper(StudentMapper.class);
        Student student = mapper.selectByPrimaryKey(2);

以上,最簡單的mybatis示例已經完成!