初識Mybatis框架,實現增刪改查等操做(動態拼接和動態修改)

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

這個問題在個人另外一篇blogs中有專門的講解,今天我主要是帶着你們來探討一下如何簡單的使用Mybatis這個框架數據庫

可能有的朋友知道,Mybatis中是經過配置文件來實現這個的,這裏面有不少的東西,咱們就一點一點的講吧express

咱們想要配置成功,首要的就是jar包,先從官網下載相應的jar包做爲程序的支撐apache

 

有了jar包以後我麼就來看看咱們程序的主要的搭建session

具體類的內容以下mybatis

Student    Classoracle

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  Classapp

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.xmlless

<?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的一些高級內容的講解我會繼續在後中爲你們持續講解

相關文章
相關標籤/搜索