搭建MyBatis開(kāi)發(fā)環(huán)境及基本的CURD介紹
一、MyBatis概述
首先就是之前Java web中的三層結(jié)構(gòu)
界面層: 和用戶(hù)打交道的, 接收用戶(hù)的請(qǐng)求參數(shù), 顯示處理結(jié)果的。(jsp ,html ,servlet)業(yè)務(wù)邏輯層: 接收了界面層傳遞的數(shù)據(jù),計(jì)算邏輯,調(diào)用數(shù)據(jù)庫(kù),獲取數(shù)據(jù)數(shù)據(jù)訪問(wèn)層: 就是訪問(wèn)數(shù)據(jù)庫(kù), 執(zhí)行對(duì)數(shù)據(jù)的查詢(xún),修改,刪除等等的
三層中對(duì)應(yīng)的包:
界面層: controller包 (servlet)業(yè)務(wù)邏輯層: service 包(XXXService類(lèi))數(shù)據(jù)訪問(wèn)層: dao包(XXXDao類(lèi))
三層中類(lèi)的交互
用戶(hù)使用界面層--> 業(yè)務(wù)邏輯層--->數(shù)據(jù)訪問(wèn)層(持久層)-->數(shù)據(jù)庫(kù)(mysql)
三層對(duì)應(yīng)的處理框架
界面層---servlet---springmvc(框架) 業(yè)務(wù)邏輯層---service類(lèi)--spring(框架) 數(shù)據(jù)訪問(wèn)層---dao類(lèi)--mybatis(框架)1. MyBatis 解決的主要問(wèn)題
減輕使用 JDBC 的復(fù)雜性,不用編寫(xiě)重復(fù)的創(chuàng)建 Connetion , Statement ; 不用編寫(xiě)關(guān)閉資源代碼。直接使用 java 對(duì)象,表示結(jié)果數(shù)據(jù)。讓開(kāi)發(fā)者專(zhuān)注 SQL 的處理。 其他分心的工作由 MyBatis 代勞
總的來(lái)說(shuō),mybatis就是增強(qiáng)版的JDBC
二、快速開(kāi)始一個(gè) MyBatis
首先就是搭建MyBatis的環(huán)境
1. 創(chuàng)建mysql數(shù)據(jù)庫(kù)和表
數(shù)據(jù)庫(kù)名:ssm,表名:student
2. 創(chuàng)建maven工程
這個(gè)就不詳細(xì)的說(shuō)了,可以看之前寫(xiě)的文章
https://www.jb51.net/article/189570.htm
3. 在pom.xml文件中添加信息
主要就是mybatis依賴(lài),和mysql驅(qū)動(dòng)
還有就是在build標(biāo)簽里添加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依賴(lài)--> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis</artifactId> <version>3.5.1</version> </dependency> <!--mysql驅(qū)動(dòng)--> <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 文件都會(huì)掃描到--> <include>**/*.properties</include> <include>**/*.xml</include> </includes> <filtering>false</filtering> </resource> </resources> </build></project>
4. 編寫(xiě)對(duì)應(yīng)的實(shí)體類(lèi)
創(chuàng)建包c(diǎn)om.md.domain,創(chuàng)建Student類(lèi)
package com.md.domain;/** * @author MD * @create 2020-08-05 9:04 */// 和數(shù)據(jù)庫(kù)的表名一樣,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; }// 對(duì)應(yīng)的set和get方法以及toString() }
5. 編寫(xiě)Dao接口:StudentDao
創(chuàng)建包: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 { // 查詢(xún)Student表中所有數(shù)據(jù) public List<Student> selectStudents();}
6. 編寫(xiě) Dao 接口 Mapper 映射文件 StudentDao.xml
注意:
在接口所在的包:com.md.dao里創(chuàng)建文件 StudentDao.xml這個(gè)映射文件的名稱(chēng)要和接口的名稱(chēng)一樣
特別注意里面寫(xiě)的備注信息
<?xml version='1.0' encoding='UTF-8' ?><!--指定的約束文件,mybatis-3-mapper.dtd是約束文件的名稱(chēng),擴(kuò)展名是dtd約束文件的作用:限制、檢查當(dāng)前文件中出現(xiàn)的標(biāo)簽,屬性必須符號(hào)mybatis的要求--><!DOCTYPE mapper PUBLIC '-//mybatis.org//DTD Mapper 3.0//EN' 'http://mybatis.org/dtd/mybatis-3-mapper.dtd'><!--mapper:是當(dāng)前文件的根標(biāo)簽namespace :必須有值,自定義的唯一字符串,推薦使用: dao 接口的全限定名稱(chēng)--><mapper namespace='com.md.dao.StudentDao'> <!-- <select>: 查詢(xún)數(shù)據(jù), 標(biāo)簽中必須是 select 語(yǔ)句 id: sql 語(yǔ)句的自定義名稱(chēng),推薦使用 dao 接口中方法名稱(chēng), 使用名稱(chēng)表示要執(zhí)行的 sql 語(yǔ)句 resultType: 查詢(xún)語(yǔ)句的返回結(jié)果數(shù)據(jù)類(lèi)型,使用全限定類(lèi)名 --> <select resultType='com.md.domain.Student'> <!-- 要執(zhí)行的 sql 語(yǔ)句 --> select id,name,email,age from student </select> <!-- <update>:表示更新數(shù)據(jù)庫(kù)的操作,里面寫(xiě)的是update sql語(yǔ)句 <insert>: <delete>: --></mapper>
7. 創(chuàng)建 MyBatis 主配置文件
注意:
在項(xiàng)目 src/main 下創(chuàng)建 resources 目錄,設(shè)置 resources 目錄為 resources root 創(chuàng)建主配置文件:名稱(chēng)為 mybatis.xml特別注意里面寫(xiě)的備注信息
<?xml version='1.0' encoding='UTF-8' ?><!--mybatis的主配置文件,上面還是約束文件的說(shuō)明--><!DOCTYPE configuration PUBLIC '-//mybatis.org//DTD Config 3.0//EN' 'http://mybatis.org/dtd/mybatis-3-config.dtd'><!--根標(biāo)簽 --><configuration> <!-- 配置 mybatis 環(huán)境 數(shù)據(jù)庫(kù)的連接信息,default:必須和某個(gè)environment的id值一樣 ,告訴mybatis使用那個(gè)數(shù)據(jù)庫(kù)的連接信息,也就是訪問(wèn)那個(gè)數(shù)據(jù)庫(kù) --> <environments default='mysql'> <!-- 一個(gè)數(shù)據(jù)庫(kù)的配置信息 id: 數(shù)據(jù)源的名稱(chēng),可以自定義 --> <environment id='mysql'> <!-- 配置事務(wù)類(lèi)型:使用 JDBC 事務(wù)(使用 Connection 的提交和回滾) --> <transactionManager type='JDBC'/> <!-- 數(shù)據(jù)源 dataSource :創(chuàng)建數(shù)據(jù)庫(kù) Connection 對(duì)象 type: POOLED 使用數(shù)據(jù)庫(kù)的連接池 --> <dataSource type='POOLED'> <!-- 連接數(shù)據(jù)庫(kù)的四個(gè)要素,是固定的 --> <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 要執(zhí)行的 sql 語(yǔ)句的位置 一個(gè)標(biāo)簽指定一個(gè)文件的位置 --> <mapper resource='com/md/dao/StudentDao.xml'/> </mappers></configuration>
如果是高版本的mysql,中文亂碼可以使用下面的
支持中文的 urljdbc:mysql://localhost:3306/ssm?useUnicode=true&characterEncoding=utf-8
基本就是如下的結(jié)構(gòu)
8. 創(chuàng)建測(cè)試類(lèi) TestMybatis
在src/test/java/com/md/ 創(chuàng)建TestMybatis
特別注意里面寫(xiě)的備注信息
主要關(guān)心第六步和第七步,前面的都是一樣的,后面直接封裝方法
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 { // 測(cè)試方法 @Test public void testSelect() throws IOException { // 訪問(wèn)mybatis讀取student數(shù)據(jù) //1.定義mybatis主配置文件的名稱(chēng), 從類(lèi)路徑的根開(kāi)始(target/clasess),編譯之后的目錄 String config = 'mybatis.xml'; //2.讀取這個(gè)config表示的文件 InputStream in = Resources.getResourceAsStream(config); //3.創(chuàng)建了SqlSessionFactoryBuilder對(duì)象 SqlSessionFactoryBuilder builder = new SqlSessionFactoryBuilder(); //4.創(chuàng)建SqlSessionFactory對(duì)象 SqlSessionFactory factory = builder.build(in); //5.獲取SqlSession對(duì)象,從SqlSessionFactory中獲取SqlSession SqlSession sqlSession = factory.openSession(); //6.【重要】指定要執(zhí)行的sql語(yǔ)句的標(biāo)識(shí)。 sql映射文件中的namespace + '.' + 標(biāo)簽的id值// String sqlId = 'com.md.dao.StudentDao'+'.'+'selectStudents'; String sqlId = 'com.md.dao.StudentDao.selectStudents'; //7.【重要】執(zhí)行sql語(yǔ)句,通過(guò)sqlId找到語(yǔ)句 List<Student> studentList = sqlSession.selectList(sqlId); //8.輸出結(jié)果 studentList.forEach( stu -> System.out.println(stu)); //9.關(guān)閉SqlSession對(duì)象 sqlSession.close(); }}
如果運(yùn)行找不到mybatis.xml文件,先檢查是否在pom.xml中配置下面的信息沒(méi),
在pom.xml下的build標(biāo)簽中
<resources> <resource> <directory>src/main/java</directory><!--所在的目錄--> <includes><!--包括目錄下的.properties,.xml 文件都會(huì)掃描到--> <include>**/*.properties</include> <include>**/*.xml</include> </includes> <filtering>false</filtering> </resource></resources>
不行的話(huà)就重啟項(xiàng)目,通常就可以解決問(wèn)題
9. 配置日志功能
mybatis.xml 文件加入日志配置,可以在控制臺(tái)輸出執(zhí)行的 sql 語(yǔ)句和參數(shù)
在根標(biāo)簽里面添加
<settings> <!-- 設(shè)置mybatis的輸出日志--> <setting name='logImpl' value='STDOUT_LOGGING' /> </settings>
然后運(yùn)行項(xiàng)目,就可以在控制臺(tái)看到輸出了
三、總結(jié)
實(shí)現(xiàn)步驟
新建一個(gè)student表 加入maven的mybatis坐標(biāo),以及mysql驅(qū)動(dòng)的坐標(biāo),看pom.xml文件中的信息 創(chuàng)建實(shí)體類(lèi),Student,保存表中一行的數(shù)據(jù) 創(chuàng)建持久層的dao接口,定義操作數(shù)據(jù)庫(kù)的方法 創(chuàng)建一個(gè)mybatis使用的配置文件,叫做sql映射文件(mapper文件),一般一個(gè)表一個(gè)sql的映射文件,是xml文件,并且這個(gè)文件是在接口所在的目錄,文件名和接口名一致 創(chuàng)建mybatis的主配置文件,一個(gè)項(xiàng)目就一個(gè)主配置文件,主配置文件提供了數(shù)據(jù)庫(kù)的連接信息和sql映射文件的位置信息 創(chuàng)建測(cè)試類(lèi),使用mybatis訪問(wèn)數(shù)據(jù)庫(kù)四、insert
1. StudentDao 接口中增加方法
// 插入方法 public int insertStudent(Student student);
2. StudentDao.xml 加入 sql 語(yǔ)句
<!-- 插入的時(shí)候要注意占位符,就是你傳入對(duì)象的屬性值--> <insert > insert into student values(#{id},#{name},#{email},#{age}) </insert>
3. 增加測(cè)試方法
前面的都一樣,主要就是第六步之后的
package com.md;public class TestMybatis { // 測(cè)試方法 @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.【重要】指定要執(zhí)行的sql語(yǔ)句的標(biāo)識(shí)。 sql映射文件中的namespace + '.' + 標(biāo)簽的id值// String sqlId = 'com.md.dao.StudentDao'+'.'+'selectStudents'; String sqlId = 'com.md.dao.StudentDao.insertStudent'; //7.【重要】執(zhí)行sql語(yǔ)句,通過(guò)sqlId找到語(yǔ)句 // 第一個(gè)參數(shù)是執(zhí)行的sql語(yǔ)句,第二個(gè)是對(duì)象 int i = sqlSession.insert(sqlId,new Student(1004,'劉桑','ls@qq.com',18)); // 需要注意,mybatis默認(rèn)不是自動(dòng)提交事務(wù),所以在寫(xiě)完insert、update、delete之后,手動(dòng)的提交事務(wù) sqlSession.commit(); //8.輸出結(jié)果 System.out.println('執(zhí)行insert影響的行數(shù):'+i); //9.關(guān)閉SqlSession對(duì)象 sqlSession.close(); }}
需要注意,mybatis默認(rèn)不是自動(dòng)提交事務(wù),所以在寫(xiě)完insert、update、delete之后,手動(dòng)的提交事務(wù)
五、update
和上面的都差不多,就直接寫(xiě)主要的步驟
1. StudentDao 接口中增加方法
int updateStudent(Student student);
2. StudentDao.xml 增加 sql 語(yǔ)句
<update id='updateStudent'>update student set age = #{age} where id=#{id}</update>
3. 增加測(cè)試方法
//5. 創(chuàng)建保存數(shù)據(jù)的對(duì)象Student student = new Student();student.setId(1005);// 要修改的 idstudent.setAge(30); // 要修改的年齡值//6. 執(zhí)行 更新 updateint rows = session.update('com.bjpowernode.dao.StudentDao.updateStudent',student);//7. 提交事務(wù)session.commit();System.out.println(' 修改記錄的行數(shù):'+rows);//8. 關(guān)閉 SqlSessionsession.close();
六、delete
1. StudentDao 接口中增加方法
int deleteStudent(int id);
2. StudentDao.xml 增加 sql 語(yǔ)句
<delete id='deleteStudent'>delete from student where id=#{studentId}</delete>
3. 增加測(cè)試方法
//5. 刪除的 idint id = 1001;//6. 執(zhí)行刪除 deleteint rows = session.delete('com.bjpowernode.dao.StudentDao.deleteStudent',id);//7. 提交事務(wù)session.commit();System.out.println(' 修改記錄的行數(shù):'+rows);//8. 關(guān)閉 SqlSessionsession.close();
總結(jié)
到此這篇關(guān)于搭建MyBatis開(kāi)發(fā)環(huán)境及基本的CURD的文章就介紹到這了,更多相關(guān)搭建MyBatis開(kāi)發(fā)環(huán)境及基本的CURD內(nèi)容請(qǐng)搜索好吧啦網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持好吧啦網(wǎng)!
相關(guān)文章:
1. Oracle數(shù)據(jù)庫(kù)表空間超詳細(xì)介紹2. MySQL存儲(chǔ)引擎選擇InnoDB還是MyISAM3. SQL Server中單引號(hào)的兩種處理技巧4. 快速刪除ORACLE重復(fù)記錄5. mysql如何獲取時(shí)間整點(diǎn)6. idea連接SQL Server數(shù)據(jù)庫(kù)的詳細(xì)圖文教程7. Sqlserver之死鎖查詢(xún)以及批量解鎖的實(shí)現(xiàn)方法8. SQL SERVER數(shù)據(jù)庫(kù)開(kāi)發(fā)之存儲(chǔ)過(guò)程的應(yīng)用9. mysql 模糊查詢(xún) concat()的用法詳解10. MySQL 的啟動(dòng)和連接方式實(shí)例分析
