1. 程式人生 > >IntelliJ IDEA 開發mybatis上手

IntelliJ IDEA 開發mybatis上手

目錄

 

引言

配置檔案

db.properties( 配置資料庫資訊)

mybatis.xml(配置資料庫載入資訊)

sql.xml(撰寫sql語句)

撰寫程式碼

studentBean實體類

MybatisUtil操作類

main入口

參考文獻


引言

mybatis目前是業內主流操作資料庫的框架,相比JDBC而言,不需要啥都寫。首先建立一個maven工程,輸入相應的groupId和ArtifactId,記住這兩個值留待後用。首先看看整個工程的目錄結構,之後逐一介紹:

本專案以MySQL為資料庫,建立好工程後在pom.xml 中加入mybatis和mysql依賴庫

<?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</groupId>
    <artifactId>sogou</artifactId>
    <version>1.0-SNAPSHOT</version>
    <build>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <configuration>
                    <source>7</source>
                    <target>7</target>
                </configuration>
            </plugin>
        </plugins>
    </build>
    <dependencies>
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis</artifactId>
            <version>3.4.6</version>
        </dependency>
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.46</version>
        </dependency>
    </dependencies>
</project>

配置檔案

在resource目錄下建立三個檔案db.properties( 配置資料庫資訊)\mybatis.xml(配置資料庫載入資訊)\sql.xml(撰寫sql語句)。注意事項全部在程式碼中有註釋,不在贅述。

db.properties( 配置資料庫資訊)

mysql.driver = com.mysql.jdbc.Driver
mysql.url = jdbc:mysql://*.*.*.*:3306/mydb?characterEncoding=utf-8
mysql.username = ***
mysql.password = ***

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>
        <!-- 載入資料庫屬性檔案 -->
        <properties resource="db.properties"/>

        <!-- 可設定多個連線環境資訊 -->
        <environments default="mysql_developer">
            <!-- 連線環境資訊,取一個任意唯一的名字 -->
            <environment id="mysql_developer">
                <!-- mybatis使用jdbc事務管理方式 -->
                <transactionManager type="jdbc"/>
                <!-- mybatis使用連線池方式來獲取連線 -->
                <dataSource type="pooled">
                    <!-- 配置與資料庫連結資訊 -->
                    <property name="driver" value="${mysql.driver}"/>
                    <property name="url" value="${mysql.url}"/>
                    <property name="username" value="${mysql.username}"/>
                    <property name="password" value="${mysql.password}"/>
                </dataSource>
            </environment>
        </environments>
        <mappers>
            <!--對映sql操作的檔案 -->
            <mapper resource="sql.xml"/>
        </mappers>

</configuration>

sql.xml(撰寫sql語句)

裡面寫sql語句,如下建立一個查詢返回的實體對映studentMap和Insert插入操作以及findByCondition條件查詢

<?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">

<!-- namespace名稱空間,必須與建立maven groupId + artifactId組成
否則,在配置檔案mybatis.xml中無法找到對映檔案
-->
<mapper namespace="com.xzy">
    <!-- resultMap標籤:對映實體類與資料庫表
         type屬性:表示實體類名
         id屬性:為實體類與資料庫表對映的唯一名字
    -->
    <resultMap type="studentBean" id="studentMap">
        <!-- id標籤:對映主鍵屬性;result標籤:對映非主鍵屬性
             property屬性:實體bean類屬性名
             column屬性:資料庫表的欄位名
             順序無關,欄位需對應
        -->
        <id property="studentID" column="studentID"/>
        <result property="age" column="age"/>
        <result property="name" column="name"/>
    </resultMap>

    <insert id="Insert" parameterType="studentBean">
        INSERT INTO student (name, age, studentID) VALUES (#{name},#{age},#{studentID});
    </insert>
    <!--條件查詢,注意部分字元需轉義,如小於,<![CDATA[ < ]]>
    resultMap為上訴建立的實體物件
    -->
    <select id="findByCondition" parameterType="int" resultMap="studentMap">
        select * from student where age <![CDATA[ < ]]>#{age};
    </select>
</mapper>

撰寫程式碼

studentBean實體類

該實體類與資料庫中表對應,建構函式需引數順序需與資料庫中表欄位先後順序相對應。本人並未發現mybatis能創表,所以事先得將表建立,本例資料表為student表(studentID[主鍵],name,age),如圖

public class studentBean {
    private String name;
    private String studentID;
    private int age;

    /**
     * 建構函式引數的順序必須和資料庫欄位的順序一致,否則在執行查詢時
     * 返回的物件無法轉成該物件,從而報類似No constructor found in studentBean matching [java.lang.String, java.lang.String, java.lang.Integer]
     * 異常
     * **/
    public studentBean(String name, String studentID, int age) {
        this.name = name;
        this.age = age;
        this.studentID = studentID;
    }

    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 String getStudentID() {
        return studentID;
    }

    public void setStudentID(String studentID) {
        this.studentID = studentID;
    }

    @Override
    public String toString() {
        return "studentBean{" +
                "name='" + name + '\'' +
                ", studentID='" + studentID + '\'' +
                ", age=" + age +
                '}';
    }
}

MybatisUtil操作類

用於操作mysql資料庫,插入和條件查詢的呼叫需sql.xml裡面名稱空間加ID組成

import java.io.IOException;
import java.io.Reader;
import java.util.List;

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 MybatisUtil {
    private static ThreadLocal<SqlSession> threadLocal = new ThreadLocal<>();
    private static SqlSessionFactory sqlSessionFactory;
    /**
     * 載入位於src/mybatis.xml配置檔案
     */
    static{
        try {
            Reader reader = Resources.getResourceAsReader("mybatis.xml");
            sqlSessionFactory = new SqlSessionFactoryBuilder().build(reader);
        } catch (IOException e) {
            e.printStackTrace();
            throw new RuntimeException(e);
        }
    }
    /**
     * 禁止外界通過new方法建立
     */
    private MybatisUtil(){}
    /**
     * 獲取SqlSession
     */
    public static SqlSession getSqlSession(){
        //從當前執行緒中獲取SqlSession物件
        SqlSession sqlSession = threadLocal.get();
        //如果SqlSession物件為空
        if(sqlSession == null){
            //在SqlSessionFactory非空的情況下,獲取SqlSession物件
            sqlSession = sqlSessionFactory.openSession();
            //將SqlSession物件與當前執行緒繫結在一起
            threadLocal.set(sqlSession);
        }
        //返回SqlSession物件
        return sqlSession;
    }
    /**
     * 關閉SqlSession與當前執行緒分開
     */
    public static void closeSqlSession(){
        //從當前執行緒中獲取SqlSession物件
        SqlSession sqlSession = threadLocal.get();
        //如果SqlSession物件非空
        if(sqlSession != null){
            //關閉SqlSession物件
            sqlSession.close();
            //分開當前執行緒與SqlSession物件的關係,目的是讓GC儘早回收
            threadLocal.remove();
        }
    }
    public static void insert(studentBean student){
        //得到連線物件
        SqlSession sqlSession = MybatisUtil.getSqlSession();
        try{
            //對映檔案的名稱空間.SQL片段的ID,就可以呼叫對應的對映檔案中的SQL
            sqlSession.insert("com.xzy.Insert", student);
            sqlSession.commit();
        }catch(Exception e){
            e.printStackTrace();
            sqlSession.rollback();
        }finally{
            MybatisUtil.closeSqlSession();
        }
    }

    public static List<studentBean> selectByConf(int conf){
        SqlSession sqlSession = MybatisUtil.getSqlSession();
        List list = null;
        try{
            list = sqlSession.selectList("com.xzy.findByCondition", conf);
        }catch(Exception e){
            e.printStackTrace();
            sqlSession.rollback();
        }finally{
            MybatisUtil.closeSqlSession();
        }
        return list;
    }

}

main入口

進行了連結測試,插入測試和條件查詢測試

import java.sql.Connection;
import java.util.List;

public class testMain {
    public static void main(String[] args) {
        Connection conn = MybatisUtil.getSqlSession().getConnection();
        System.out.println(conn!=null?"連線成功":"連線失敗");
        studentBean bean = new studentBean("小李子", "20180809005", 21);
        MybatisUtil.insert(bean);
        List<studentBean> studentList = MybatisUtil.selectByConf(23);
        if (studentList != null){
            for (studentBean student : studentList){
                System.out.println(student.toString());
            }
        }
    }
}

終端輸出顯示為:

連線成功
studentBean{name='小紅', studentID='20180809001', age=21}
studentBean{name='小芳', studentID='20180809002', age=20}
studentBean{name='小李子', studentID='20180809005', age=21}

參考文獻

https://segmentfault.com/a/1190000013661958#articleHeader13
https://blog.csdn.net/lucia_fanchen/article/details/49386327
http://www.mybatis.org/mybatis-3/zh/getting-started.html