初識MyBatis框架

x-l-t-x發表於2020-11-04

1.什麼是MyBatis?
mybatis是一個基於ORM(物件關係對映)的資料訪問層框架。

2.何為框架呢?
框架本質還是java程式,只不過框架是被一些牛人將原始及底層程式碼進行封裝,將封裝後的程式打包提供開發人員使用。幫助開發者提高開發的效率,同時也能提升專案的效能。
在這裡插入圖片描述
資料訪問層–通常我們在做專案的時候,會把一個專案分成3個部分,這3個部分分別是:
2.1 控制層[web層]----用來做資料的導航【Servlet、Struts2、SpringMVC】
2.1 業務層----用來處理相關功能的具有實現業務。【Spring】
2.3 資料訪問層[資料持久層]—用來訪問資料庫資料。【JDBC、Hibernate、MyBatis】
早期JavaWeb的3大框架—SSH[Struts2-Spring-Hibernate] 現在流行的JavaWeb的3大框架—SSM[SpringMVC-Spring-MyBatis]

3. 什麼是ORM?
ORM—物件關係對映
我們在訪問資料庫的時候所編寫的都是Java程式,Java程式只認識Java物件,而我們所訪問的資料庫大多數都是關係型資料庫,那麼這時Java程式要想訪問關係型資料庫,那麼就需要將Java物件轉換成關係型資料,才能被資料庫認識。這時我們可以認為一個Java類就是關係型資料庫中的一張資料表,Java類中的成員變數是資料庫表中的一個列,Java類建立的Java物件就是資料庫表中的一行記錄。這時將Java物件對應成為資料庫表記錄的過程就是物件關係對映。
4. 為什麼要使用MyBatis?
4.1 為了簡化資料庫訪問操作,提高開發的效率,提升專案的效能,增加程式的可維護性。
4.2. 當我們使用Java程式控制Java物件的時候,資料庫中的資料表記錄會隨之變化。(將原來通過java程式訪問資料庫表的操作,簡化成通過java程式訪問java物件)。

5.簡單使用MyBatis框架開發一個使用者資訊系統
5.1 建立資料庫表結構

create table tb_student(
stuid int primary key auto_increment,
stuname varchar(30),
stupassword varchar(20),
stuage int,
stuaddress varchar(30)
);

5.2 使用IDEA建立普maven專案,完善專案結構

5.3 pox.xml檔案匯入依賴

<!-- https://mvnrepository.com/artifact/mysql/mysql-connector-java -->
    <dependency>
      <groupId>mysql</groupId>
      <artifactId>mysql-connector-java</artifactId>
      <version>5.1.38</version>
    </dependency>
    <!-- https://mvnrepository.com/artifact/org.mybatis/mybatis -->
    <dependency>
      <groupId>org.mybatis</groupId>
      <artifactId>mybatis</artifactId>
      <version>3.4.6</version>
    </dependency>

5.4 根據資料庫表結構建立java實體類

package com.qing.bean;

public class StudentBean {
    private int stuid;
    private String stuname;
    private String stupassword;
    private int stuage;
    private String stuaddress;

    public int getStuid() {
        return stuid;
    }

    public void setStuid(int stuid) {
        this.stuid = stuid;
    }

    public String getStuname() {
        return stuname;
    }

    public void setStuname(String stuname) {
        this.stuname = stuname;
    }

    public String getStupassword() {
        return stupassword;
    }

    public void setStupassword(String stupassword) {
        this.stupassword = stupassword;
    }

    public int getStuage() {
        return stuage;
    }

    public void setStuage(int stuage) {
        this.stuage = stuage;
    }

    public String getStuaddress() {
        return stuaddress;
    }

    public void setStuaddress(String stuaddress) {
        this.stuaddress = stuaddress;
    }
}

5.5 在src/main/resources中編寫資料庫資原始檔 mydate.properties

mydriver = com.mysql.jdbc.Driver
myurl = jdbc:mysql://127.0.0.1:3306/test
myusername = root
mypassword = 123456

5.6 建立資料庫訪問介面

package com.qing.mapper;
import com.qing.bean.StudentBean;
import java.util.List;
public interface StudentMapper {
    //新增資訊
    boolean insertStudent(StudentBean studentBean);

    //修改資訊
    boolean updateStudentId(int stuid);

    //刪除資訊
    boolean deleteStudent(int stuid);

    //根據id查詢
    StudentBean seleteStudentId(int stuid);

    //查詢所有
    List<StudentBean> selectStudent();
}

5.7 在src/main/resources中編寫sql對映檔案 StudentMapper.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="com.qing.mapper.StudentMapper">
    <insert id="insertStudent" parameterType="com.qing.bean.StudentBean">
        insert into tb_student values (null,#{stuname},#{stupassword},#{stuage},#{stuaddress});
    </insert>
    <update id="updateStudent" parameterType="int">
        update tb_student set stuname=#{stuname},stupassword=#{stupassword},stuage=#{stuage},stuaddress=#{stuaddress} where stuid=#{stuid};
    </update>
    <delete id="deleteStudent" parameterType="int">
        delete from tb_student where stuid=#{stuid};
    </delete>
    <resultMap id="studentMap" type="com.qing.bean.StudentBean">
        <id column="stuid" property="stuid"></id>
        <result column="stuname" property="stuname"></result>
        <result column="stupassword" property="stupassword"></result>
        <result column="stuage" property="stuage"></result>
        <result column="stuaddress" property="stuaddress"></result>
    </resultMap>
    <select id="seleteStudentId" parameterType="int" resultMap="studentMap">
    select * from tb_student where stuid=#{stuid};
</select>
    <select id="selectStudent" resultMap="studentMap">
        select * from tb_student;
    </select>
</mapper>

5.8 在src/main/resources中建立 mybatis-config.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>
    <!-- 配置引入資料連線字串的資原始檔 -->
    <properties resource="mydate.properties"></properties>
    <!-- 配置mybatis預設的連線資料庫環境 -->
    <environments default="development">
        <environment id="development">
            <transactionManager type="JDBC"></transactionManager>
            <dataSource type="POOLED">
                <property name="driver" value="${mydriver}"></property>
                <property name="url" value="${myurl}"></property>
                <property name="username" value="${myusername}"></property>
                <property name="password" value="${mypassword}"></property>
            </dataSource>
        </environment>
    </environments>
    <!-- 配置mybatis資料訪問介面的SQL對映檔案路徑 -->
    <mappers>
        <mapper resource="StudentMapper.xml"></mapper>
    </mappers>

</configuration>

5.9 測試

package com.qing.test;
import com.qing.bean.StudentBean;
import com.qing.mapper.StudentMapper;
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 java.util.List;
public class TestMain {
    /**
     * 新增資訊
     */
    public static void insertStudent() {
        //定義SqlSession物件
        SqlSession sqlSession = null;
        try {
            //通過SqlSessionFactoryBuilder類建立出SqlSessionFactory物件
            SqlSessionFactory sqlSessionFactory = new
                    SqlSessionFactoryBuilder().build(Resources.getResourceAsReader("mybatis-config.xml"));
            //從SqlSessionFactory中取得一個SqlSession物件
            sqlSession = sqlSessionFactory.openSession();
            //通過資料訪問介面呼叫新增方法
            StudentMapper studentMapper = sqlSession.getMapper(StudentMapper.class);
            StudentBean studentBean = new StudentBean();
            studentBean.setStuname("烤紅薯");
            studentBean.setStupassword("111111");
            studentBean.setStuage(22);
            studentBean.setStuaddress("長豐國際");
            studentMapper.insertStudent(studentBean);
            sqlSession.commit();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            sqlSession.close();
        }
    }

    /**
     * 修改資訊
     * @param stuid
     */
    public static void updateStudentId(int stuid) {
        SqlSession sqlSession = null;
        try {
            SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(Resources.getResourceAsReader("mybatis-config.xml"));
            sqlSession = sqlSessionFactory.openSession();
            StudentMapper studentMapper = sqlSession.getMapper(StudentMapper.class);
            StudentBean studentBean = new StudentBean();
            studentBean.setStuid(stuid);
            studentBean.setStuname("地瓜");
            studentBean.setStupassword("123321");
            studentBean.setStuage(122);
            studentBean.setStuaddress("曲江");
            studentMapper.updateStudentId(stuid);
            sqlSession.commit();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            sqlSession.close();
        }
    }

    /**
     * 刪除資訊
     * @param stuid
     */
    public static void deleteStudentId(int stuid) {
        SqlSession sqlSession = null;
        try {
            SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(Resources.getResourceAsReader("mybatis-config.xml"));
            sqlSession = sqlSessionFactory.openSession();
            StudentMapper studentMapper = sqlSession.getMapper(StudentMapper.class);
            StudentBean studentBean = new StudentBean();
            studentBean.setStuid(9);
            studentMapper.deleteStudent(stuid);
            sqlSession.commit();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            sqlSession.close();
        }
    }

    /**
     * 根據id查詢資訊
     * @param stuid
     */
    public static void selectStudentId(int stuid) {
        SqlSession sqlSession = null;
        try {
            SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(Resources.getResourceAsReader("mybatis-config.xml"));
            sqlSession = sqlSessionFactory.openSession();
            StudentMapper studentMapper = sqlSession.getMapper(StudentMapper.class);
            StudentBean studentBean = studentMapper.seleteStudentId(8);
            System.out.println(studentBean.getStuname() + "\t" + studentBean.getStuaddress());
            sqlSession.commit();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            sqlSession.close();
        }
    }

    /**
     * 查詢所有資訊
     */
    public static void selectStudent() {
        SqlSession sqlSession = null;
        try {
            SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(Resources.getResourceAsReader("mybatis-config.xml"));
            sqlSession = sqlSessionFactory.openSession();
            StudentMapper studentMapper = sqlSession.getMapper(StudentMapper.class);
            List<StudentBean> studentlist = studentMapper.selectStudent();
            for (StudentBean studentBean : studentlist) {
                System.out.println(studentBean.getStuname() + "\t" + studentBean.getStupassword() + "\t" + studentBean.getStuage() + "\t" + studentBean.getStuaddress());
            }
            sqlSession.commit();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            sqlSession.close();
        }
    }

    /**
     * 測試
     * @param args
     */
    public static void main(String[] args) {
        //insertStudent();
        updateStudentId(4);
        //deleteStudentId(9);
        //selectStudentId(8);
        //selectStudent();
    }
}

相關文章