初識Mybatis框架,實現增刪改查等操作

来源:http://www.cnblogs.com/liujiayun/archive/2016/08/27/5807425.html
-Advertisement-
Play Games

此第一次接觸Mybatis框架確實是有點不適應,特別是剛從Hibernate框架轉轉型過來,那麼為什麼要使用Mybatis框架,Mybatis框架和Hibernate框架又有什麼異同呢? 這個問題在我的另一篇blogs中有專門的講解,今天我主要是帶著大家來探討一下如何簡單的使用Mybatis這個框架 ...


此第一次接觸Mybatis框架確實是有點不適應,特別是剛從Hibernate框架轉轉型過來,那麼為什麼要使用Mybatis框架,Mybatis框架和Hibernate框架又有什麼異同呢?

這個問題在我的另一篇blogs中有專門的講解,今天我主要是帶著大家來探討一下如何簡單的使用Mybatis這個框架

可能有的朋友知道,Mybatis中是通過配置文件來實現這個的,這裡面有很多的東西,我們就一點一點的講吧

我們想要配置成功,首要的就是jar包,先從官網下載相應的jar包作為程式的支撐

 

有了jar包之後我麽就來看看我們程式的主要的搭建

具體類的內容如下

Student    Class

package entity;
/*
 * 學生類
 * */
public class Student {
    //學生編號
    private Integer sid;
    //學生名稱
    private String sname;
    //學生性別
    private String sex;
    
    
    
    
    
    
    
    
    
    
    public Student() {
    }
    public Student(String sname, String sex) {
        this.sname = sname;
        this.sex = sex;
    }
    public Integer getSid() {
        return sid;
    }
    public void setSid(Integer sid) {
        this.sid = sid;
    }
    public String getSname() {
        return sname;
    }
    public void setSname(String sname) {
        this.sname = sname;
    }
    public String getSex() {
        return sex;
    }
    public void setSex(String sex) {
        this.sex = sex;
    }
    
}

 

Grade  Class

package entity;
/*
 * 班級類
 * */
public class Grade {
    //班級編號
    private Integer gid;
    //班級名稱
    private String gname;
    //班級描述
    private String gdesc;
    
    
    
    
    public Grade() {
    }
    public Grade(Integer gid, String gname, String gdesc) {
        this.gid = gid;
        this.gname = gname;
        this.gdesc = gdesc;
    }
    public Integer getGid() {
        return gid;
    }
    public void setGid(Integer gid) {
        this.gid = gid;
    }
    public String getGname() {
        return gname;
    }
    public void setGname(String gname) {
        this.gname = gname;
    }
    public String getGdesc() {
        return gdesc;
    }
    public void setGdesc(String gdesc) {
        this.gdesc = gdesc;
    }
    
}

接下來我麽就要配置我們的主要配置文件了,主要是指定我們要連接的資料庫和具體連接操作

Configuration.xml

<?xml version="1.0" encoding="UTF-8" ?>
<!--

       Copyright 2009-2012 the original author or authors.

       Licensed under the Apache License, Version 2.0 (the "License");
       you may not use this file except in compliance with the License.
       You may obtain a copy of the License at

          http://www.apache.org/licenses/LICENSE-2.0

       Unless required by applicable law or agreed to in writing, software
       distributed under the License is distributed on an "AS IS" BASIS,
       WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
       See the License for the specific language governing permissions and
       limitations under the License.

-->
<!DOCTYPE configuration
    PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
    "http://mybatis.org/dtd/mybatis-3-config.dtd">

<configuration>
<!-- 
  <settings>
    <setting name="useGeneratedKeys" value="false"/>
    <setting name="useColumnLabel" value="true"/>
  </settings>

  <typeAliases>
    <typeAlias alias="UserAlias" type="org.apache.ibatis.submitted.complex_property.User"/>
  </typeAliases> -->
  <environments default="development">
    <environment id="development">
      <transactionManager type="JDBC">
        <property name="" value=""/>
      </transactionManager>
      <dataSource type="UNPOOLED">
        <property name="driver" value="oracle.jdbc.OracleDriver"/>
        <property name="url" value="jdbc:oracle:thin:@localhost:1521:orcl"/>
        <property name="username" value="practice"/>
        <property name="password" value="123"/>
      </dataSource>
    </environment>
  </environments>
  
   <mappers>
    <mapper resource="config/Student.xml"/>
  </mappers> 

</configuration>

 

其實最主要的是如下圖所示

 

到這裡為止,所有的準備工作基本上就已經是完成了

接下來,使用Mybatis框架來實現我們的具體操作‘

1.查詢所有學生信息

 因為Mybatis是屬於一種半自動化的框架技術所以呢sql是我們手動書寫的,這也是Mybatis的一大特點

我們可以寫出具體的實體配置文件

Student.xml

<?xml version="1.0" encoding="UTF-8"?>
<!--

       Copyright 2009-2012 the original author or authors.

       Licensed under the Apache License, Version 2.0 (the "License");
       you may not use this file except in compliance with the License.
       You may obtain a copy of the License at

          http://www.apache.org/licenses/LICENSE-2.0

       Unless required by applicable law or agreed to in writing, software
       distributed under the License is distributed on an "AS IS" BASIS,
       WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
       See the License for the specific language governing permissions and
       limitations under the License.

-->

<!DOCTYPE mapper
    PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
    "http://mybatis.org/dtd/mybatis-3-mapper.dtd">

<mapper namespace="Student">

  <resultMap type="entity.Student" id="StudentResult">
    <id column="sid" jdbcType="INTEGER" property="sid"/>
    <result column="sname" jdbcType="VARCHAR" property="sname"/>
    <result column="sex" jdbcType="VARCHAR" property="sex"/>
  </resultMap>
    
    <select id="selectAllStu"  resultMap="StudentResult">
        select * from Student
    </select>
 
</mapper>

 

既然我們寫了sql也指定了相應的實體類,那麼我們到現在為止還並沒有用到它,所以我們還需要在主配置文件中添加實體配置文件的引用

 

經過以上的步驟, 我們查詢全部學生的配置文件基本上就已經完成了,現在我們來進行一道測試

/*
     * 1.1 查詢所有的學生信息
     * */
    @Test
    public void OneTest() throws Exception{
        //通過配置文件獲取到資料庫連接信息
        Reader reader = Resources.getResourceAsReader("config/Configuration.xml");
        //通過配置信息構建一個SessionFactory工廠
        SqlSessionFactory sqlsessionfactory=new SqlSessionFactoryBuilder().build(reader);
        //通過SessionFaction打開一個回話通道
        SqlSession session = sqlsessionfactory.openSession();
        //調用配置文件中的sql語句
        List<Student> list = session.selectList("Student.selectAllStu");
        //遍歷查詢出來的結果
        for (Student stu : list) {
            System.out.println(stu.getSname());
        }
        
        session.close();
    }

執行之後的語句如下

 這樣我們使用Mybatis查詢所有學生信息就完成了

 

2.帶條件查詢動態Sql拼接

/*
     *1.2 帶條件查詢信息(動態Sql拼接)
     * */
    @Test
    public void selectAllStuByWhere() throws Exception{
        //通過配置文件獲取到資料庫連接信息
        Reader reader = Resources.getResourceAsReader("config/Configuration.xml");
        //通過配置信息構建一個SessionFactory工廠
        SqlSessionFactory sqlsessionfactory=new SqlSessionFactoryBuilder().build(reader);
        //通過SessionFaction打開一個回話通道
        SqlSession session = sqlsessionfactory.openSession();
        //準備一個學生對象作為參數
        Student student=new Student();
        student.setSname("3");
        //調用配置文件中的sql語句
        List<Student> list = session.selectList("Student.selectAllStuByWhere",student);
        //遍歷查詢出來的結果
        for (Student stu : list) {
            System.out.println(stu.getSname());
        }
        
        session.close();
    }

 

 

小配置配置文件信息

<?xml version="1.0" encoding="UTF-8"?>
<!--

       Copyright 2009-2012 the original author or authors.

       Licensed under the Apache License, Version 2.0 (the "License");
       you may not use this file except in compliance with the License.
       You may obtain a copy of the License at

          http://www.apache.org/licenses/LICENSE-2.0

       Unless required by applicable law or agreed to in writing, software
       distributed under the License is distributed on an "AS IS" BASIS,
       WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
       See the License for the specific language governing permissions and
       limitations under the License.

-->

<!DOCTYPE mapper
    PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
    "http://mybatis.org/dtd/mybatis-3-mapper.dtd">

<mapper namespace="Student">

  <resultMap type="entity.Student" id="StudentResult">
    <id column="sid" jdbcType="INTEGER" property="sid"/>
    <result column="sname" jdbcType="VARCHAR" property="sname"/>
    <result column="sex" jdbcType="VARCHAR" property="sex"/>
  </resultMap>
    
    <!-- 簡單查詢所有信息 -->
     <select id="selectAllStu"  resultMap="StudentResult">
        select sid,sname,sex,gid from Student 
    </select> 
    
    <!--動態拼接Sql  -->
     <select id="selectAllStuByWhere" parameterType="entity.Student"  resultMap="StudentResult">
        select sid,sname,sex,gid from Student where 1=1
        <if test="sname!=null and !&quot;&quot;.equals(sname.trim())">
            and sname like '%'|| #{sname}|| '%' <!-- 模糊查詢 -->
            <!-- and sname = #{sname} -->
        </if>
        
     </select>
</mapper>

 

執行之後的結果就是

 

3.新增學生信息

/*
     * 1.3 新增學生信息
     * 
     * */
    @Test
    public void InsertStuInfo() throws Exception{
        //通過配置文件獲取配置信息
        Reader reader = Resources.getResourceAsReader("config/Configuration.xml");
        //構建一個SessionFactory,傳入配置文件
        SqlSessionFactory factory=new SqlSessionFactoryBuilder().build(reader);
        //獲取session
        SqlSession session = factory.openSession();
        //準備參數對象
        Student stu=new Student();
        stu.setSname("巴黎的雨季");
        stu.setSex("");
        //調用添加方法
        int count = session.insert("Student.InsertStuInfo", stu);
        if(count>0){
            System.out.println("添加成功");
        }else{
            System.out.println("添加失敗");
        }
        //提交
        session.commit();
        //關閉
        session.close();
    }

 

在小配置中增加一個節點

<!-- 新增學生信息 -->
     <insert id="InsertStuInfo" parameterType="entity.Student" >
         insert into Student values(SEQ_NUM.Nextval,#{sname},#{sex},1)
     </insert>

執行之後結果為

後續的刪除和修改代碼基本上和新增是一致的,只是調用的sql語句不同,所以後續我就不做詳細的解釋了,只將代碼擺出來,詳細大家都能夠看得明白!!

 

4.刪除學生信息根據id

/*
     * 1.4根據SID刪除學生信息
     * */
    @Test
    public void DeleteStuBySid()throws Exception{
        //通過配置文件獲取配置信息
        Reader reader = Resources.getResourceAsReader("config/Configuration.xml");
        //構建一個SessionFactory,傳入配置文件
        SqlSessionFactory factory=new SqlSessionFactoryBuilder().build(reader);
        //獲取session
        SqlSession session = factory.openSession();
        //準備參數
        int sid=2;
        //調用刪除方法
        int count = session.delete("Student.DeleteStuBySid", sid);
        if(count>0){
            System.out.println("刪除成功");
        }else{
            System.out.println("刪除失敗");
        }
        //提交
        session.commit();
        //關閉
        session.close();
    }

 

需要在配置文件中新增的是

 <!-- 刪除學生信息 -->
     <insert id="DeleteStuBySid" parameterType="int">
         delete from Student where sid=#{sid}
     <!--或者是     delete from Student where sid=#{_parameter} -->
     </insert>

 

5.根據SID修改學生信息

/*
     * 1.5根據SID修改學生信息
     * 
     * */
    @Test
    public void UpdateStuBySid()throws Exception{
        //通過配置文件獲取配置信息
        Reader reader = Resources.getResourceAsReader("config/Configuration.xml");
        //構建一個SessionFactory,傳入配置文件
        SqlSessionFactory factory=new SqlSessionFactoryBuilder().build(reader);
        //獲取session
        SqlSession session = factory.openSession();
        //準備參數對象
        Student stu=new Student();
        stu.setSid(1);
        stu.setSname("綠茵");
        stu.setSex("");
        //調用刪除方法
        int count = session.update("Student.UpdateStuBySid", stu);
        if(count>0){
            System.out.println("修改成功");
        }else{
            System.out.println("修改失敗");
        }
        //提交
        session.commit();
        //關閉
        session.close();
    }

 

需要在配置文件中添加的是

 

 <!-- 根據SID修改學生信息 -->
     <update id="UpdateStuBySid" parameterType="entity.Student" >
     <!--     update Student set sname=#{sname},sex=#{sex} where sid=#{sid} -->
          update Student
         <set>
             <if test="sname!=null">
                 sname=#{sname},
             </if>
             <if test="sex!=null">
                 sex=#{sex},
             </if>
         </set>
         where sid=#{sid} 
     </update>

 

 

 

  

 以上我們就簡單的完成了對Mybatis的增、刪、改、查的基本操作了,關於Mybatis的一些高級內容的講解我會繼續在後中為大家持續講解

 


您的分享是我們最大的動力!

-Advertisement-
Play Games
更多相關文章
  • 時隔 15.6 個月,終於發佈了一個新版本 v1.1.0。 新版本除了包含了這些日子收集到的無數的小改進及 bug fixes,也有一些新功能。本文嘗試從使用者的角度,簡單介紹一下這些功能和沿由。 ...
  • 在學習python之前,我也學習過C ,C++ ,Java ,PHP ,javascript,前端也學習過。但是在學習Python的這段時間里,多多少少也感覺到Python在語法方面的不同和特殊性。 今天,我們就來聊聊Python都有哪些語法引起過我們的好奇。 1.註釋方面,一般C , Java , ...
  • A集成代碼生成器 [正反雙向(單表、主表、明細表、樹形表,開發利器)+快速構建表單; freemaker模版技術 ,0個代碼不用寫,生成完整的一個模塊,帶頁面、建表sql腳本,處理類,service等完整模塊B 集成阿裡巴巴資料庫連接池druid; 資料庫連接池 阿裡巴巴的 druid。Druid在 ...
  • (一)Hibernate入門 通俗的話來說:Hibernate是用於面向對象操控資料庫,對JDBC進行輕量級封裝。(在java世界中傳統的來說是JDBC訪問資料庫。) 1)Hibernate定性:對象關係映射框架。(底層依舊是JDBC) 2)Hibernate框架的結構圖 解析:Java Appli ...
  • 程式 程式的本質是對現實生活的建模,反映真實世界。程式是對現實的抽象。那我們拿現實與程式對比著看,在現實生活,最重要的是處理人與人之間的關係,處理好人與人之間的關係,生活不會太難,而反映到程式是,在程式里最重要,最關鍵是處理類與類之間的關係,處理不好類與類之間的關係,到後期,一個項目將會分崩離析。在 ...
  • 學習過Hibernate框架的伙伴們很容易就能簡單的配置各種映射關係(Hibernate框架的映射關係在我的blogs中也有詳細的講解),但是在Mybatis框架中我們又如何去實現 一對多的關係映射呢? 其實很簡單 首先我們照常先準備前期的環境(具體解釋請 參考初識Mybatis進行增、刪、改、查 ...
  • 學習了Hibernate和Mybatis,但是一直不太清楚他們兩者的區別的聯繫,今天在網上翻了翻,就做了一下總結,希望對大家有幫助! 原文:http://blog.csdn.net/firejuly/article/details/8190229 第一章 Hibernate與MyBatis Hibe ...
  • 在Lua中,我們可以通過table+function來模擬實現類。 而要模擬出類,元表(metatable)和__index元方法是必不可少的。 為一個表設置元表的方法: table = {} metatable = {} setmetatable(table, metatable) 或者 tabl ...
一周排行
    -Advertisement-
    Play Games
  • 示例項目結構 在 Visual Studio 中創建一個 WinForms 應用程式後,項目結構如下所示: MyWinFormsApp/ │ ├───Properties/ │ └───Settings.settings │ ├───bin/ │ ├───Debug/ │ └───Release/ ...
  • [STAThread] 特性用於需要與 COM 組件交互的應用程式,尤其是依賴單線程模型(如 Windows Forms 應用程式)的組件。在 STA 模式下,線程擁有自己的消息迴圈,這對於處理用戶界面和某些 COM 組件是必要的。 [STAThread] static void Main(stri ...
  • 在WinForm中使用全局異常捕獲處理 在WinForm應用程式中,全局異常捕獲是確保程式穩定性的關鍵。通過在Program類的Main方法中設置全局異常處理,可以有效地捕獲並處理未預見的異常,從而避免程式崩潰。 註冊全局異常事件 [STAThread] static void Main() { / ...
  • 前言 給大家推薦一款開源的 Winform 控制項庫,可以幫助我們開發更加美觀、漂亮的 WinForm 界面。 項目介紹 SunnyUI.NET 是一個基於 .NET Framework 4.0+、.NET 6、.NET 7 和 .NET 8 的 WinForm 開源控制項庫,同時也提供了工具類庫、擴展 ...
  • 說明 該文章是屬於OverallAuth2.0系列文章,每周更新一篇該系列文章(從0到1完成系統開發)。 該系統文章,我會儘量說的非常詳細,做到不管新手、老手都能看懂。 說明:OverallAuth2.0 是一個簡單、易懂、功能強大的許可權+可視化流程管理系統。 有興趣的朋友,請關註我吧(*^▽^*) ...
  • 一、下載安裝 1.下載git 必須先下載並安裝git,再TortoiseGit下載安裝 git安裝參考教程:https://blog.csdn.net/mukes/article/details/115693833 2.TortoiseGit下載與安裝 TortoiseGit,Git客戶端,32/6 ...
  • 前言 在項目開發過程中,理解數據結構和演算法如同掌握蓋房子的秘訣。演算法不僅能幫助我們編寫高效、優質的代碼,還能解決項目中遇到的各種難題。 給大家推薦一個支持C#的開源免費、新手友好的數據結構與演算法入門教程:Hello演算法。 項目介紹 《Hello Algo》是一本開源免費、新手友好的數據結構與演算法入門 ...
  • 1.生成單個Proto.bat內容 @rem Copyright 2016, Google Inc. @rem All rights reserved. @rem @rem Redistribution and use in source and binary forms, with or with ...
  • 一:背景 1. 講故事 前段時間有位朋友找到我,說他的窗體程式在客戶這邊出現了卡死,讓我幫忙看下怎麼回事?dump也生成了,既然有dump了那就上 windbg 分析吧。 二:WinDbg 分析 1. 為什麼會卡死 窗體程式的卡死,入口門檻很低,後續往下分析就不一定了,不管怎麼說先用 !clrsta ...
  • 前言 人工智慧時代,人臉識別技術已成為安全驗證、身份識別和用戶交互的關鍵工具。 給大家推薦一款.NET 開源提供了強大的人臉識別 API,工具不僅易於集成,還具備高效處理能力。 本文將介紹一款如何利用這些API,為我們的項目添加智能識別的亮點。 項目介紹 GitHub 上擁有 1.2k 星標的 C# ...