一、MyBatis概述
首先就是之前Java web中的三層結構
界面層: 和用戶打交道的, 接收用戶的請求參數, 顯示處理結果的。(jsp ,html ,servlet)
業務邏輯層: 接收了界面層傳遞的數據,計算邏輯,調用數據庫,獲取數據
數據訪問層: 就是訪問數據庫, 執行對數據的查詢,修改,刪除等等的
三層中對應的包:
界面層: controller包 (servlet)
業務邏輯層: service 包(XXXService類)
數據訪問層: dao包(XXXDao類)
三層中類的交互
用戶使用界面層--> 業務邏輯層--->數據訪問層(持久層)-->數據庫(mysql)
三層對應的處理框架
- 界面層---servlet---springmvc(框架)
- 業務邏輯層---service類--spring(框架)
- 數據訪問層---dao類--mybatis(框架)
1. MyBatis 解決的主要問題
減輕使用 JDBC 的復雜性,不用編寫重復的創建 Connetion , Statement ; 不用編寫關閉資源代碼。
直接使用 java 對象,表示結果數據。讓開發者專注 SQL 的處理。 其他分心的工作由 MyBatis 代勞
總的來說,mybatis就是增強版的JDBC
二、快速開始一個 MyBatis
首先就是搭建MyBatis的環境
1. 創建mysql數據庫和表
數據庫名:ssm,表名:student
2. 創建maven工程
這個就不詳細的說了,可以看之前寫的文章
https://www.cnblogs.com/mengd/p/13436355.html
3. 在pom.xml文件中添加信息
主要就是mybatis依賴,和mysql驅動
還有就是在build標簽里添加maven插件,方便之后使用
<?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>com.md</groupId>
<artifactId>01-hello-mybatis</artifactId>
<version>1.0-SNAPSHOT</version>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<maven.compiler.source>1.8</maven.compiler.source>
<maven.compiler.target>1.8</maven.compiler.target>
</properties>
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.11</version>
<scope>test</scope>
</dependency>
<!--mybatis依賴-->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.5.1</version>
</dependency>
<!--mysql驅動-->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.9</version>
</dependency>
</dependencies>
<build>
<resources>
<resource>
<directory>src/main/java</directory><!--所在的目錄-->
<includes><!--包括目錄下的.properties,.xml 文件都會掃描到-->
<include>**/*.properties</include>
<include>**/*.xml</include>
</includes>
<filtering>false</filtering>
</resource>
</resources>
</build>
</project>
4. 編寫對應的實體類
創建包com.md.domain,創建Student類
package com.md.domain;
/**
* @author MD
* @create 2020-08-05 9:04
*/
// 和數據庫的表名一樣,
public class Student {
// 定義屬性,屬性名和列名一致
private Integer id;
private String name;
private String email;
private Integer age;
public Student() {
}
public Student(Integer id, String name, String email, Integer age) {
this.id = id;
this.name = name;
this.email = email;
this.age = age;
}
// 對應的set和get方法以及toString()
}
5. 編寫Dao接口:StudentDao
創建包:com.md.dao
package com.md.dao;
import com.md.domain.Student;
import java.util.List;
/**
* @author MD
* @create 2020-08-05 9:07
*/
public interface StudentDao {
// 查詢Student表中所有數據
public List<Student> selectStudents();
}
6. 編寫 Dao 接口 Mapper 映射文件 StudentDao.xml
注意:
在接口所在的包:com.md.dao里創建文件 StudentDao.xml
這個映射文件的名稱要和接口的名稱一樣
特別注意里面寫的備注信息
<?xml version="1.0" encoding="UTF-8" ?>
<!--指定的約束文件,mybatis-3-mapper.dtd是約束文件的名稱,擴展名是dtd
約束文件的作用:限制、檢查當前文件中出現的標簽,屬性必須符號mybatis的要求
-->
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<!--
mapper:是當前文件的根標簽
namespace :必須有值,自定義的唯一字符串,推薦使用: dao 接口的全限定名稱
-->
<mapper namespace="com.md.dao.StudentDao">
<!--
<select>: 查詢數據, 標簽中必須是 select 語句
id: sql 語句的自定義名稱,推薦使用 dao 接口中方法名稱,
使用名稱表示要執行的 sql 語句
resultType: 查詢語句的返回結果數據類型,使用全限定類名
-->
<select id="selectStudents" resultType="com.md.domain.Student">
<!-- 要執行的 sql 語句 -->
select id,name,email,age from student
</select>
<!--
<update>:表示更新數據庫的操作,里面寫的是update sql語句
<insert>:
<delete>:
-->
</mapper>
7. 創建 MyBatis 主配置文件
注意:
在項目 src/main 下創建 resources 目錄,設置 resources 目錄為 resources root
- 創建主配置文件:名稱為 mybatis.xml
特別注意里面寫的備注信息
<?xml version="1.0" encoding="UTF-8" ?>
<!--
mybatis的主配置文件,上面還是約束文件的說明
-->
<!DOCTYPE configuration
PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-config.dtd">
<!--根標簽 -->
<configuration>
<!-- 配置 mybatis 環境
數據庫的連接信息,default:必須和某個environment的id值一樣
,告訴mybatis使用那個數據庫的連接信息,也就是訪問那個數據庫
-->
<environments default="mysql">
<!--
一個數據庫的配置信息
id: 數據源的名稱,可以自定義
-->
<environment id="mysql">
<!-- 配置事務類型:使用 JDBC 事務(使用 Connection 的提交和回滾) -->
<transactionManager type="JDBC"/>
<!-- 數據源 dataSource :創建數據庫 Connection 對象
type: POOLED 使用數據庫的連接池
-->
<dataSource type="POOLED">
<!-- 連接數據庫的四個要素,是固定的 -->
<property name="driver" value="com.mysql.jdbc.Driver"/>
<property name="url" value="jdbc:mysql://localhost:3306/ssm"/>
<property name="username" value="root"/>
<property name="password" value="123456"/>
</dataSource>
</environment>
</environments>
<!--sql映射文件的位置-->
<mappers>
<!-- 告訴 mybatis 要執行的 sql 語句的位置
一個標簽指定一個文件的位置
-->
<mapper resource="com/md/dao/StudentDao.xml"/>
</mappers>
</configuration>
如果是高版本的mysql,中文亂碼可以使用下面的
支持中文的 url
jdbc:mysql://localhost:3306/ssm?useUnicode=true&characterEncoding=utf-8
基本就是如下的結構
8. 創建測試類 TestMybatis
在src/test/java/com/md/ 創建TestMybatis
特別注意里面寫的備注信息
主要關心第六步和第七步,前面的都是一樣的,后面直接封裝方法
package com.md;
import com.md.domain.Student;
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.List;
/**
* @author MD
* @create 2020-08-05 10:27
*/
public class TestMybatis {
// 測試方法
@Test
public void testSelect() throws IOException {
// 訪問mybatis讀取student數據
//1.定義mybatis主配置文件的名稱, 從類路徑的根開始(target/clasess),編譯之后的目錄
String config = "mybatis.xml";
//2.讀取這個config表示的文件
InputStream in = Resources.getResourceAsStream(config);
//3.創建了SqlSessionFactoryBuilder對象
SqlSessionFactoryBuilder builder = new SqlSessionFactoryBuilder();
//4.創建SqlSessionFactory對象
SqlSessionFactory factory = builder.build(in);
//5.獲取SqlSession對象,從SqlSessionFactory中獲取SqlSession
SqlSession sqlSession = factory.openSession();
//6.【重要】指定要執行的sql語句的標識。 sql映射文件中的namespace + "." + 標簽的id值
// String sqlId = "com.md.dao.StudentDao"+"."+"selectStudents";
String sqlId = "com.md.dao.StudentDao.selectStudents";
//7.【重要】執行sql語句,通過sqlId找到語句
List<Student> studentList = sqlSession.selectList(sqlId);
//8.輸出結果
studentList.forEach( stu -> System.out.println(stu));
//9.關閉SqlSession對象
sqlSession.close();
}
}
如果運行找不到mybatis.xml文件,先檢查是否在pom.xml中配置下面的信息沒,
在pom.xml下的build標簽中
<resources>
<resource>
<directory>src/main/java</directory><!--所在的目錄-->
<includes><!--包括目錄下的.properties,.xml 文件都會掃描到-->
<include>**/*.properties</include>
<include>**/*.xml</include>
</includes>
<filtering>false</filtering>
</resource>
</resources>
不行的話就重啟項目,通常就可以解決問題
9. 配置日志功能
mybatis.xml 文件加入日志配置,可以在控制台輸出執行的 sql 語句和參數
在根標簽里面添加
<settings>
<!-- 設置mybatis的輸出日志-->
<setting name="logImpl" value="STDOUT_LOGGING" />
</settings>
然后運行項目,就可以在控制台看到輸出了
三、總結
實現步驟
- 新建一個student表
- 加入maven的mybatis坐標,以及mysql驅動的坐標,看pom.xml文件中的信息
- 創建實體類,Student,保存表中一行的數據
- 創建持久層的dao接口,定義操作數據庫的方法
- 創建一個mybatis使用的配置文件,叫做sql映射文件(mapper文件),一般一個表一個sql的映射文件,是xml文件,並且這個文件是在接口所在的目錄,文件名和接口名一致
- 創建mybatis的主配置文件,一個項目就一個主配置文件,主配置文件提供了數據庫的連接信息和sql映射文件的位置信息
- 創建測試類,使用mybatis訪問數據庫
四、insert
1. StudentDao 接口中增加方法
// 插入方法
public int insertStudent(Student student);
2. StudentDao.xml 加入 sql 語句
<!-- 插入的時候要注意占位符,就是你傳入對象的屬性值-->
<insert id="insertStudent" >
insert into student values(#{id},#{name},#{email},#{age})
</insert>
3. 增加測試方法
前面的都一樣,主要就是第六步之后的
package com.md;
public class TestMybatis {
// 測試方法
@Test
public void testInsert() throws IOException {
String config = "mybatis.xml";
InputStream in = Resources.getResourceAsStream(config);
SqlSessionFactoryBuilder builder = new SqlSessionFactoryBuilder();
SqlSessionFactory factory = builder.build(in);
SqlSession sqlSession = factory.openSession();
//6.【重要】指定要執行的sql語句的標識。 sql映射文件中的namespace + "." + 標簽的id值
// String sqlId = "com.md.dao.StudentDao"+"."+"selectStudents";
String sqlId = "com.md.dao.StudentDao.insertStudent";
//7.【重要】執行sql語句,通過sqlId找到語句
// 第一個參數是執行的sql語句,第二個是對象
int i = sqlSession.insert(sqlId,new Student(1004,"劉桑","ls@qq.com",18));
// 需要注意,mybatis默認不是自動提交事務,所以在寫完insert、update、delete之后,手動的提交事務
sqlSession.commit();
//8.輸出結果
System.out.println("執行insert影響的行數:"+i);
//9.關閉SqlSession對象
sqlSession.close();
}
}
需要注意,mybatis默認不是自動提交事務,所以在寫完insert、update、delete之后,手動的提交事務
五、update
和上面的都差不多,就直接寫主要的步驟
1. StudentDao 接口中增加方法
int updateStudent(Student student);
2. StudentDao.xml 增加 sql 語句
<update id="updateStudent">
update student set age = #{age} where id=#{id}
</update>
3. 增加測試方法
//5. 創建保存數據的對象
Student student = new Student();
student.setId(1005);// 要修改的 id
student.setAge(30); // 要修改的年齡值
//6. 執行 更新 update
int rows = session.update(
"com.bjpowernode.dao.StudentDao.updateStudent",student);
//7. 提交事務
session.commit();
System.out.println(" 修改記錄的行數:"+rows);
//8. 關閉 SqlSession
session.close();
六、delete
1. StudentDao 接口中增加方法
int deleteStudent(int id);
2. StudentDao.xml 增加 sql 語句
<delete id="deleteStudent">
delete from student where id=#{studentId}
</delete>
3. 增加測試方法
//5. 刪除的 id
int id = 1001;
//6. 執行刪除 delete
int rows = session.delete(
"com.bjpowernode.dao.StudentDao.deleteStudent",id);
//7. 提交事務
session.commit();
System.out.println(" 修改記錄的行數:"+rows);
//8. 關閉 SqlSession
session.close();