Mybatis 快速入門(XML方式)第一天

導讀

架構原理圖

 

說明

mybatis配置文件

  1. SqlMapConfig.xml,此文件爲mybatis的全局配置文件,配置了mybatis的運行環境等信息
  2. XXXMapper.xml,此文件做爲mybatis的sql映射文件,文件中配置了操做數據庫的CRUD語句。須要在SqlMapConfig.xml中加載

SqlSessionFactory

  1. 經過mybatis環境等配置信息構造SqlSessionFactory,既會話工廠

***跟底層源碼查看建立SqlSessionFactory流程***

注:底層如何獲取標籤值,請自行研究(劇透:for循環遍歷XML獲取標籤中的值,而後放入Map)!~java

SqlSession

  1. 經過會員工廠建立SqlSession即會話,程序經過SqlSession會話接口對數據庫進行CRUD操做。

Executor執行器

  mybatis底層自定義了Executor執行器接口來具體操做數據庫,Executor接口有兩個實現,一個是基本執行器(默認),一個緩存執行器,SqlSession底層是經過executor接口操做數據庫mysql

Mapped Statement

  他是mybatis一個底層封裝對象,包裝了mybatis配置信息及XXXMapper.xml映射文件等。XXXMapper.xml文件中一個個select/insert/update/delete標籤對應一個Mapped Statement對象sql

原始JDBC代碼

  原始JDBC和mybatis操做數據庫數據,與上面架構圖流程相對應。數據庫

public class JDBCTest {

    public static void main(String[] args) {
        Connection connection = null;
        PreparedStatement preparedStatement = null;
        ResultSet resultSet = null;

        try {
            // 加載數據庫驅動
            Class.forName("com.mysql.jdbc.Driver");

            // 經過驅動管理類獲取數據庫連接connection = DriverManager
            connection = DriverManager.getConnection(
                              "jdbc:mysql://localhost:3306/mybatis?characterEncoding=utf-8",
                             "root", 
                              "root"
                              );

            // 定義sql語句 ?表示佔位符
            String sql = "select * from user where username = ?";
            // 獲取預處理 statement
            preparedStatement = connection.prepareStatement(sql);
            
            // 設置參數,第一個參數爲 sql 語句中參數的序號(從 1 開始),第二個參數爲設置的
            preparedStatement.setString(1, "王五");
            // 向數據庫發出 sql 執行查詢,查詢出結果集
            resultSet = preparedStatement.executeQuery();
            // 遍歷查詢結果集
            while (resultSet.next()) {
                System.out.println(
                                  resultSet.getString("id") 
                                  + " " + 
                                  resultSet.getString("username")
                     );
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            // 釋放資源
            if (resultSet != null) {
                try {
                    resultSet.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
            if (preparedStatement != null) {
                try {
                    preparedStatement.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
            if (connection != null) {
                try {
                    connection.close();
                } catch (SQLException e) {
                    // TODO Auto-generated catch block e.printStackTrace();
                }
            }
        }
    }
}

Mybatis 入門基礎

表結構

 表數據

Mybatis環境搭建 

添加依賴

pom.xmlapache

<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/maven-v4_0_0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <groupId>com.cyb</groupId>
    <artifactId>mybatis</artifactId>
    <packaging>war</packaging>
    <version>0.0.1-SNAPSHOT</version>
    <name>mybatis Maven Webapp</name>
    <url>http://maven.apache.org</url>
    <dependencies>
        <!-- mybatis依賴 -->
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis</artifactId>
            <version>3.4.6</version>
        </dependency>
        <!-- mysql依賴 -->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>8.0.20</version>
        </dependency>

        <!-- 單元測試 -->
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.12</version>
        </dependency>
    </dependencies>
    <build>
        <finalName>mybatis</finalName>
    </build>
</project>

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>
    <!-- 引入外部配置文件 -->
    <properties resource="db.properties"></properties>
    <!-- 數據庫連接相關 -->
    <environments default="development">
        <environment id="development">
            <transactionManager type="JDBC" />
            <dataSource type="POOLED">
                <property name="driver" value="${db.driver}" />
                <property name="url" value="${db.url}" />
                <property name="username" value="${db.username}" />
                <property name="password" value="${db.password}" />
            </dataSource>
        </environment>
    </environments>
    <mappers>
        <!-- 添加映射文件 -->
        <mapper resource="UserMapper.xml" />
    </mappers>
</configuration>

db.properties緩存

db.driver=com.mysql.jdbc.Driver
db.url=jdbc:mysql://127.0.0.1:3306/cyb
db.username=root
db.password=root

UserMapper.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">
<!-- namespace:爲了分類管理映射文件中的MappedStatement -->
<mapper namespace="test">
<select id="queryUserById" parameterType="int" resultType="com.cyb.mybatis.demo.User">
        select * from user where id = #{id} 
    </select>
</mapper>

User.java

package com.cyb.mybatis.demo;

import java.util.Date;

public class User {
    private int id;
    private String username;
    private Date birthday;
    private int sex;
    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 Date getBirthday() {
        return birthday;
    }
    public void setBirthday(Date birthday) {
        this.birthday = birthday;
    }
    public int getSex() {
        return sex;
    }
    public void setSex(int sex) {
        this.sex = sex;
    }
    public String getAddress() {
        return address;
    }
    public void setAddress(String address) {
        this.address = address;
    }
    @Override
    public String toString() {
        return "User [id=" + id + ", username=" + username + ", birthday=" + birthday + ", sex=" + sex + ", address="
                + address + "]";
    }
}

MybatisDemo.java

package com.cyb.mybatis.demo;

import java.io.InputStream;
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.Before;
import org.junit.Test;

public class MybatisDemo {

    private SqlSessionFactory sqlSessionFactory;

    @Before
    public void init() throws Exception {
        //指定全局配置文件路徑
        String resource = "SqlMapConfig.xml";
        //加載資源文件(包括全局文件和映射文件)
        InputStream inputStream = Resources.getResourceAsStream(resource);
        //使用構建者模式建立SqlSessionFactory
        sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
    }

    @Test
    public void testSelect() {
        //由SqlSessionFactory工廠去建立SqlSession(會話)
        SqlSession sqlSession = sqlSessionFactory.openSession();
        //調用SqlSession接口,去實現數據庫的CRUD
        User user = sqlSession.selectOne("test.queryUserById", 1);
        System.out.println(user);
        //釋放資源
        sqlSession.close();
    }
}

項目結構

測試

功能實現

根據用戶id查詢一個用戶信息

根據用戶名稱模糊查詢用戶信息列表

添加用戶

更新用戶

刪除用戶

相關文章
相關標籤/搜索