Mybatis 快速入門(XML方式)第一天
阿新 • • 發佈:2020-05-16
導讀
架構原理圖
說明
mybatis配置檔案
- SqlMapConfig.xml,此檔案為mybatis的全域性配置檔案,配置了mybatis的執行環境等資訊
- XXXMapper.xml,此檔案作為mybatis的sql對映檔案,檔案中配置了操作資料庫的CRUD語句。需要在SqlMapConfig.xml中載入
SqlSessionFactory
- 通過mybatis環境等配置資訊構造SqlSessionFactory,既會話工廠
***跟底層原始碼檢視建立SqlSessionFactory流程***
注:底層如何獲取標籤值,請自行研究(劇透:for迴圈遍歷XML獲取標籤中的值,然後放入Map)!~
SqlSession
- 通過會員工廠建立SqlSession即會話,程式通過SqlSession會話介面對資料庫進行CRUD操作。
Executor執行器
mybatis底層自定義了Executor執行器介面來具體操作資料庫,Executor介面有兩個實現,一個是基本執行器(預設),一個快取執行器,SqlSession底層是通過executor介面操作資料庫
Mapped Statement
他是mybatis一個底層封裝物件,包裝了mybatis配置資訊及XXXMapper.xml對映檔案等。XXXMapper.xml檔案中一個個select/insert/update/delete標籤對應一個Mapped Statement物件。
原始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.xml
<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(); } }