天天看點

Mybatis【1】-- 第一個Mybatis程式1.架構是什麼2.Mybatis的介紹3.Mybatis和Hibernate對比4.Mybatis的結構圖:5.IDEA建立第一個程式6.總結

1.架構是什麼

  • 架構(

    Framework

    )是整個或部分系統的可重用設計,表現為一組抽象構件及構件執行個體間互動的方法;另一種定義認為,架構是可被應用開發者定制的應用骨架。前者是從應用方面而後者是從目的方面給出的定義。
  • 一個架構是一個可複用的設計構件,它規定了應用的體系結構,闡明了整個設計、協作構件之間的依賴關系、責任配置設定和控制流程,表現為一組抽象類以及其執行個體之間協作的方法,它為構件複用提供了上下文(Context)關系。是以構件庫的大規模重用也需要架構。
  • 個人了解:架構最重要的是把我們常用的,可以重複使用的功能抽象出來,不需要我們去重複寫,我們隻需要調用,或者按照規定配置,按照規則使用就可以了。這樣的缺點是很多時候我們不知道為什麼可以這樣子使用,裡面實作的細節被屏蔽掉了,這也是很多初學者很懵逼的地方,這時候追根問底就有一定必要性了。

2.Mybatis的介紹

Mybatis本來是Apache的一個開源項目

iBatis

,這個項目2010年由

Apache

遷移到了

Google

,更名為Mybatis,2013年正式遷移到

Github

Mybatis

是一個java中一個持久層的架構,在裡面封裝了jdbc操作,如果還不了解java如何使用jdbc通路資料庫,那麼可以檢視這篇文章,封裝使開發者隻需要把精力放在開發sql語句上,不用去注冊驅動,建立Connection,配置Statement,自己寫代碼管理事務等等。

Mybatis通過xml或者注解的方式将需要執行的statement配置好,通過映射将java對象與sql中的動态參數一起生成最終的sql語句,執行完之後傳回對象,其中也是映射的結果。

3.Mybatis和Hibernate對比

1.Hibernate是全自動的ORM架構,也就是完全實作了POJO和資料庫表之間的映射,會自動生成SQL。但是Mybatis不會自動生成,SQL還是需要自己寫,但是映射關系架構會自動處理,這樣一個好處就是可以看得到SQL,很多時候系統自動生成SQL并不是高效的,我們有時候需要優化SQL,或者一些複雜的查詢可能自動化的很難做到,缺點就是需要花時間寫。

2.使用XML檔案進行配置,分離了了sql與代碼,這樣比較容易維護。3.Mybatis是一個輕量級的架構。學習成本比Hibernate低很多,jar包依賴也很少,上手比較快。

4.Mybatis的結構圖:

Mybatis【1】-- 第一個Mybatis程式1.架構是什麼2.Mybatis的介紹3.Mybatis和Hibernate對比4.Mybatis的結構圖:5.IDEA建立第一個程式6.總結
Mybatis的運作機制:我們通過配置Mybatis.xml(裡面配置好資料庫,需要掃描的mapper.xml檔案等),程式會自動掃描配置好的mapper檔案,當我們請求一個接口(請求資料庫),接口會直接映射到對應的sql标簽,同時将我們所寫的配置檔案讀取并将資料庫字段與對象屬性比對(這也是映射,如果不一緻,需要自己手寫映射關系),将sql參數傳進去,然後執行相關的sql,傳回時又做了一次映射,把對象傳回給我們。當然,這麼描述是很表面的,因為mybatis還有事務,緩存等方面,以上隻是大概。
Mybatis【1】-- 第一個Mybatis程式1.架構是什麼2.Mybatis的介紹3.Mybatis和Hibernate對比4.Mybatis的結構圖:5.IDEA建立第一個程式6.總結

5.IDEA建立第一個程式

這裡我們會使用idea建立項目,如果maven沒有配置好,請參考:https://blog.csdn.net/aphysia/article/details/80363684

5.1建立mysql資料庫

使用以下的指令行:

CREATE DATABASE `test` DEFAULT CHARACTER SET utf8 COLLATE utf8_general_ci;
CREATE TABLE `student` ( `id` INT NOT NULL AUTO_INCREMENT , `name` VARCHAR(20) NOT NULL , 
`age` INT NOT NULL , `score` DOUBLE NOT NULL , PRIMARY KEY (`id`)) ENGINE = MyISAM;
           

複制

5.2 使用idea建立項目(Maven)

項目結構圖(

bean

下面放的類對應我們的資料庫裡面的

student

表,也就是它的一個實體類,

dao

包下面放着我們的資料庫的操作,

resources

下面放着我們的xml或者各種資源):

Mybatis【1】-- 第一個Mybatis程式1.架構是什麼2.Mybatis的介紹3.Mybatis和Hibernate對比4.Mybatis的結構圖:5.IDEA建立第一個程式6.總結

new

-->

Project

-->點選

Maven

Mybatis【1】-- 第一個Mybatis程式1.架構是什麼2.Mybatis的介紹3.Mybatis和Hibernate對比4.Mybatis的結構圖:5.IDEA建立第一個程式6.總結

點選

next

,

GroupId

,

ArtifactId

可以自己指定,點選下一步

Mybatis【1】-- 第一個Mybatis程式1.架構是什麼2.Mybatis的介紹3.Mybatis和Hibernate對比4.Mybatis的結構圖:5.IDEA建立第一個程式6.總結

自己指定

project name

(項目名),點選

finish

Mybatis【1】-- 第一個Mybatis程式1.架構是什麼2.Mybatis的介紹3.Mybatis和Hibernate對比4.Mybatis的結構圖:5.IDEA建立第一個程式6.總結

pom.xml

裡面添加依賴,每一個之間都是一種依賴包,選中項目右鍵-->

Maven

-->

Reimport

,這樣就可以下載下傳我們所需要的依賴了:

<dependencies>
        <!-- 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>
        <!-- junit測試包 -->
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.11</version>
            <scope>test</scope>
        </dependency>
        <!-- 日志檔案管理包 -->
        <dependency>
            <groupId>log4j</groupId>
            <artifactId>log4j</artifactId>
            <version>1.2.17</version> 
        </dependency>
        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>slf4j-api</artifactId>
            <version>1.7.12</version>
        </dependency>
        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>slf4j-log4j12</artifactId>
            <version>1.7.12</version>
        </dependency>
    </dependencies>
           

複制

為了能實作日志的列印功能,我們在pom.xml檔案中已經引入了日志dependency,在這裡還需要在

resources

檔案夾下建立配置

log4j.properties

檔案,具體配置代表什麼意思,可以參考log4j 與log4j2詳解

log4j.properties
log4j.rootLogger=DEBUG, stdout

log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=[service] %d - %c -%-4r [%t] %-5p %c %x - %m%n

#log4j.appender.R=org.apache.log4j.DailyRollingFileAppender    
#log4j.appender.R.File=../logs/service.log    
#log4j.appender.R.layout=org.apache.log4j.PatternLayout    
#log4j.appender.R.layout.ConversionPattern=[service] %d - %c -%-4r [%t] %-5p %c %x - %m%n    

#log4j.logger.com.ibatis = debug    
#log4j.logger.com.ibatis.common.jdbc.SimpleDataSource = debug    
#log4j.logger.com.ibatis.common.jdbc.ScriptRunner = debug    
#log4j.logger.com.ibatis.sqlmap.engine.impl.SqlMapClientDelegate = debug    
#log4j.logger.java.sql.Connection = debug    
log4j.logger.java.sql.Statement = debug
log4j.logger.java.sql.PreparedStatement = debug
log4j.logger.java.sql.ResultSet =debug
           

複制

配置好這些之後,前面結構圖上面寫到有一個

mybatis.xml

檔案,裡面配置了運作的環境(關于資料庫的連接配接),連接配接的資料庫可以配置多個,但是必須指定使用哪一個,這樣做的原因的世界在xml檔案進行修改不需要重新編譯,更換資料庫比較簡單,除此之外,裡面還需要配置mapper.xml,也就是映射檔案,我們要告訴它,我們将sql配置寫在哪個檔案。

mybatis.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>
    <!-- 配置運作環境 -->
    <!-- default 表示預設使用哪一個環境,可以配置多個,比如開發時的測試環境,上線後的正式環境等 -->
    <environments default="mysqlEM">    
     <environment id="mysqlEM">
      <transactionManager type="JDBC">  
      </transactionManager>
      <dataSource type="POOLED">
       <property name="driver" value="com.mysql.jdbc.Driver"/>
       <property name="url" value="jdbc:mysql://127.0.0.1:3306/test"/>
       <property name="username" value="root"/>
       <property name="password" value="123456"/>
      </dataSource>
     </environment>
     <environment id="testEM">
      <transactionManager type="JDBC">
      </transactionManager>
      <dataSource type="POOLED">
       <property name="driver" value="com.mysql.jdbc.Driver"/>
       <property name="url" value="jdbc:mysql://127.0.0.1:3306/test"/>
       <property name="username" value="root"/>
       <property name="password" value="123456"/>
      </dataSource>
     </environment>
    </environments>
    <!-- 注冊映射檔案 -->
    <mappers>
     <mapper resource="mapper.xml"/>
    </mappers>
  </configuration>
           

複制

配置好

mybatis.xml

檔案我們就需要寫sql語句,根據上面的

mybatis.xml

,我們需要寫

mapper.xml

檔案,下面的

namespace

現在可以随意命名,因為隻有一個mapper.xml檔案,sql标簽的id沒有重複,執行時就是根據id來查找的,同時這裡parameterType對應的是參數類型,類型要寫帶完整路徑名的類:

mapper.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">
<mapper namespace="abc">
 <insert id="insertStudent" parameterType="bean.Student">
  insert into student(name,age,score) values(#{name},#{age},#{score})
 </insert>
</mapper>
           

複制

在bean包下面建立與資料庫對應的

Student

類【在bean包下】(這裡先把屬性名字和資料庫的字段名一緻,如果不一緻需要自己寫映射),注意裡面的方法我們需要實作set和get方法,這個在IDEA裡面,打開目前類,右鍵-->

Gernarate

-->

setter and getter

全選就可以生成。

Student.class
package bean;
public class Student {
    // id屬性
 private Integer id;
 // 名字屬性
 private String name;
 // 年齡屬性
 private int age;
 //分數屬性
 private double score;
 // 構造方法,除了id,因為我們的id在資料庫中是自增的
 public Student( String name, int age, double score) {
  super();
  this.name = name;
  this.age = age;
  this.score = score;
 }
 public Integer getId() {
  return id;
 }
 public void setId(Integer id) {
  this.id = id;
 }
 public String getName() {
  return name;
 }
 public void setName(String name) {
  this.name = name;
 }
 public int getAge() {
  return age;
 }
 public void setAge(int age) {
  this.age = age;
 }
 public double getScore() {
  return score;
 }
 public void setScore(double score) {
  this.score = score;
 }
 @Override
 public String toString() {
  return "Student [id=" + id + ", name=" + name + ", age=" + age
    + ", score=" + score + "]";
 }
 
}

           

複制

在這裡我們需要寫一個接口,來表示操作學生資訊,先寫一個插入學生資訊的接口,那麼肯定是傳一個學生對象進去。

IStduent.class
package dao;
import bean.Student;
public interface IStudentDao {
 public void insertStu(Student student);
}

           

複制

下面就是接口的實作類(重點):

StudentDaoImpl.class
package dao;
import java.io.IOException;
import java.io.InputStream;
import bean.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;
public class StudentDaoImpl implements IStudentDao {
    // 實作插入的接口方法
 public void insertStu(Student student) {
  try {
   InputStream inputStream;
      // 讀取配置資訊的檔案
   inputStream = Resources.getResourceAsStream("mybatis.xml");
   // 由于這個檔案裡面配置了mapper.xml,架構會幫我們掃描這些mapper.xml,下面是初始化一個SqlSessionFactory對象
   SqlSessionFactory sqlSessionFactory=new SqlSessionFactoryBuilder().build(inputStream);
   // 工廠會擷取一個SqlSession對象
   SqlSession sqlSession=sqlSessionFactory.openSession();
   // 通過這個對象可以查找之前mapper.xml裡面配置好的sql的id與 `insertStudent`相等的,執行對應的sql
   sqlSession.insert("insertStudent",student);
  } catch (IOException e) {

   e.printStackTrace();
  }

 }
 
}

           

複制

測試方法,如果不了解Junit測試請參考Junit測試詳解:

MyTest.class
import bean.Student;
import dao.IStudentDao;
import dao.StudentDaoImpl;
import org.junit.Before;
import org.junit.Test;
public class MyTest {
 private IStudentDao dao;
 @Before
 public void Before(){
  dao=new StudentDaoImpl();
 }
 @Test
 public void testInsert(){
  Student student=new Student("1ADAS",23,94.6);
  dao.insertStu(student);
 }
}
           

複制

測試的結果,從最後三行我們可以看到執行的sql語句,以及參數等:

Mybatis【1】-- 第一個Mybatis程式1.架構是什麼2.Mybatis的介紹3.Mybatis和Hibernate對比4.Mybatis的結構圖:5.IDEA建立第一個程式6.總結

5.3 使用Eclipse,MyEclipse建立項目(Maven)

差別不大,直接建立java Project,如果下面沒有lib這個檔案,就要建立一個,然後把需要的包導(複制粘貼)進去,選中lib下面所有的包,右鍵-->

Build Path

-->

Add to Path

Mybatis【1】-- 第一個Mybatis程式1.架構是什麼2.Mybatis的介紹3.Mybatis和Hibernate對比4.Mybatis的結構圖:5.IDEA建立第一個程式6.總結
下面是myEclipse下面的結構圖,代碼沒有改變,需要自己下載下傳相關的包
Mybatis【1】-- 第一個Mybatis程式1.架構是什麼2.Mybatis的介紹3.Mybatis和Hibernate對比4.Mybatis的結構圖:5.IDEA建立第一個程式6.總結

聲明:這樣的寫法不是最好的,但是這是初學者最容易接受的寫法,後面會慢慢的精簡,我們到時候不需要寫接口的實作類,同時會把關于sqlSessionFactory相關的操作抽取出來成為一個工具類,就不用寫那麼多相同的代碼了。

6.總結

最後總結一下上面寫法的思路:

1.先讀取

mybatis.xml

檔案流

inputStream

,這是最重要的配置檔案,裡面的内容配置的是資料庫環境,比如連接配接哪一個資料庫連結,除此之外,還有注冊映射檔案,比如掃描哪一個檔案,我們配置的是

/mapper.xml

2.通過

inputStream

建立

sqlSessionFactory

,也就是sql會話工廠,所謂工廠,肯定是用來創造或者制造

sqlSession

的。

3.

sqlSessionFactory.openSession()

可以打開一個

sqlSession

,也就是sql會話,獲得這個操作資料庫的會話視窗。

4.通過

sqlSession

提供的方法去操作資料庫,提供方法名,和參數即可。比如

sqlSession.insert("insertStudent", student);

,這個

insertStudent

從哪裡冒出來的?當然是前面掃描

mapper.xml

的時候,

mapper.xml

裡面配置的,

insertStudent

是id,需要是唯一的,就能通過這個找到對應的sql來執行。

5.送出會話,

commit

,不一定需要,具體看資料庫的類型.

6.關閉會話,

sqlSession.close();

代碼已經放在:https://github.com/Damaer/Mybatis-Learning此文章僅代表自己(本菜鳥)學習積累記錄,或者學習筆記,如有侵權,請聯系作者删除。人無完人,文章也一樣,文筆稚嫩,在下不才,勿噴,如果有錯誤之處,還望指出,感激不盡~

技術之路不在一時,山高水長,縱使緩慢,馳而不息。

- END -