1.數(shù)據(jù)庫腳本
本文采用mysql數(shù)據(jù)庫墙杯,數(shù)據(jù)腳本如下
DROP DATABASE
IF EXISTS mybatis;
CREATE DATABASE mybatis;
USE mybatis;
DROP TABLE
IF EXISTS dept;
CREATE TABLE dept(
dept_id INT AUTO_INCREMENT PRIMARY KEY ,
dept_name NVARCHAR(50) NOT NULL
);
DROP TABLE
IF EXISTS employee;
CREATE TABLE employee(
id INT AUTO_INCREMENT PRIMARY KEY ,
`name` NVARCHAR(50) NOT NULL ,
age INT ,
birthday DATETIME ,
dept_id INT ,
CONSTRAINT fk_dept_id FOREIGN KEY(dept_id) REFERENCES dept(dept_id)
);
INSERT INTO dept(dept_name)
VALUES
('信息技術部') ,
('人事部') ,
('PCB事業(yè)部') ,
('無線終端部') ,
('測試部');
INSERT INTO employee(`name` , age , birthday , dept_id)
VALUES
('小花5760 ' , 0 , NOW() , 1) ,
('小花7238 ' , 1 , NOW() , 2) ,
('小花7985 ' , 11 , NOW() , 3) ,
('小花2438 ' , 24 , NOW() , 1) ,
('小花7386 ' , 8 , NOW() , 4) ,
('小花9787 ' , 8 , NOW() , 1) ,
('小花9711 ' , 4 , NOW() , 4) ,
('小花2119 ' , 21 , NOW() , 5);
2. 開發(fā)環(huán)境準備
開發(fā)工具為idea,使用maven構(gòu)建項目,需要一定的maven基礎勋磕,可以查看筆者之前關于maven的介紹配置http://www.reibang.com/p/2eceee248836
先來一張項目結(jié)構(gòu)圖
mapper 包主要放置mapper接口以及mapper映射文件
model 包主要放置和數(shù)據(jù)庫表對應的實體對象
util 包放置了一個關于 SQLSession 管理的類和io操作類
resources 目錄下面防止了數(shù)據(jù)庫配置文件以及mybatis核心配置文件,接下來筆者帶大家一一分析
3. pom 文件主要是mybatis和jdbc驅(qū)動的配置
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.9</version>
</dependency>
<!-- https://mvnrepository.com/artifact/mysql/mysql-connector-java -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>6.0.6</version>
</dependency>
<!-- mybatis -->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.4.5</version>
</dependency>
</dependencies>
<build>
<!--在maven中設置打包時將xml文件一起打包-->
<resources>
<resource>
<directory>src/main/java</directory>
<includes>
<include>**/*.xml</include>
</includes>
</resource>
</resources>
</build>
4. 配置文件
jdbc.properties 文件主要存放和數(shù)據(jù)庫連接相關的信息
driver=com.mysql.jdbc.Driver
url=jdbc:mysql://localhost:3306/mybatis
username=root
password=
mybatis.xml 主要是mybatis核心配置文件敢靡,
<!-- 加載屬性文件 -->
<properties resource="jdbc.properties"/>
<!-- 設置實體對象所在的包設置實體對象的別名挂滓,
默認是將該類的名稱首字母小寫,也可以使用@Alias 注解自定義
也可以使用 typeAlias 單一指定
-->
<typeAliases>
<package name="com.zzz.mybatis.model"/>
</typeAliases>
<!-- 開發(fā)配置信息 -->
<environments default="development">
<environment id="development">
<transactionManager type="JDBC"/>
<dataSource type="POOLED">
<property name="driver" value="${driver}"/>
<property name="url" value="${url}"/>
<property name="username" value="${username}"/>
<property name="password" value="${password}"/>
</dataSource>
</environment>
</environments>
<!-- mapper 接口所在的包啸胧,mybatis會自動掃描查找
也可以使用 mapper 單獨指定
-->
<mappers>
<package name="com.zzz.mybatis.mapper"/>
</mappers>
5. 先來看util包中的內(nèi)容
首先看 SqlSessionFactoryUtil赶站,這里面筆者都做了注釋,后面在專門詳細介紹纺念,以及后面即將說到的 mapper贝椿。
IoUtils 主要負責IO對象的關閉,可自行查看源碼陷谱,這里不做分析
package com.zzz.mybatis.util;
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.io.IOException;
import java.io.InputStream;
/**
* Created by tao.zeng on 2017/9/28.
*/
public class SqlSessionFactoryUtil {
private SqlSessionFactoryUtil() {
}
/**
* 主要用來創(chuàng)建 SqlSession 相當于一次會話烙博,類似于jdbc中的Connection對象
* 當程序訪問數(shù)據(jù)庫時,就需要使用該對象構(gòu)建 SqlSession烟逊,所以他應該位于整個生命周期
* 并且不希望有多個實例對象习勤,所以做成單例模式
*/
private volatile static SqlSessionFactory mSqlSessionFactory;
/**
* 返回 SqlSession 對象 該對象主要用來執(zhí)行 sql 語句
* 它應該位于一個應用的請求和操作中,注意使用時需要及時關閉回收資源
*
* @return
*/
public static SqlSession openSqlSession(){
initSqlSessionFactory();
return mSqlSessionFactory.openSession();
}
private static void initSqlSessionFactory() {
InputStream in = null;
try {
// 加載 resources 目錄下面的 mybatis.xml 文件
in = Resources.getResourceAsStream("mybatis.xml");
if (mSqlSessionFactory == null) {
synchronized (SqlSessionFactoryUtil.class) {
if (mSqlSessionFactory == null) {
// SqlSessionFactoryBuilder 主要用來生成 SqlSessionFactory 對象
// 一旦 SqlSessionFactory 構(gòu)建完成焙格,就應該將它回收图毕,所以他在方法內(nèi)部維護就好
mSqlSessionFactory = new SqlSessionFactoryBuilder().build(in);
}
}
}
} catch (IOException e) {
e.printStackTrace();
} finally {
IoUtils.close(in);
}
}
}
6.編寫 mapper 接口和 mapper映射文件
筆者在這里抽象出了一個 BaseMapper 接口,里面涉及基本的增刪改查操作眷唉,在這里用到了泛型 T 表示當前操作實體對象的類型予颤,E 表示實體對象id的類型。
package com.zzz.mybatis.mapper;
import java.util.List;
/**
* Created by tao.zeng on 2017/9/28.
*/
public interface BaseMapper<T, E> {
/**
* 查詢所有數(shù)據(jù)
*
* @return
*/
List<T> findAll();
/**
* 根據(jù) id 查詢數(shù)據(jù)
*
* @param id
* @return
*/
T findById(E id);
/**
* 保存數(shù)據(jù)
*
* @param t
* @return
*/
int save(T t);
/**
* 修改數(shù)據(jù)
*
* @param t
* @return
*/
int update(T t);
/**
* 刪除數(shù)據(jù)
*
* @param id
* @return
*/
int delete(E id);
}
如果沒有特殊的要求冬阳,單純的操作依賴于該類可以完成單表的基本操作蛤虐。
這里貼一下操作部門的mapper,納尼肝陪?空的驳庭?對,目前這里面什么都可以不用做氯窍,只需要通過泛型知道操作的是 Dept 對象已經(jīng)Dept 對象中id的類型
package com.zzz.mybatis.mapper;
import com.zzz.mybatis.model.Dept;
/**
* Created by tao.zeng on 2017/9/29.
*/
public interface DeptMapper extends BaseMapper<Dept, Long> {
}
貼出mapper映射文件
<?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 指定當前 mapper 和 Mapper對象的映射關系 -->
<mapper namespace="com.zzz.mybatis.mapper.DeptMapper">
<!-- 因為實體對象中的屬性名稱和數(shù)據(jù)庫字段名稱不一樣饲常,通過resultMap來進行映射 -->
<resultMap id="deptMapper" type="com.zzz.mybatis.model.Dept">
<!-- property 實體對象中的屬性名稱 column 數(shù)據(jù)庫中字段的名稱-->
<id property="deptId" column="dept_id"/>
<result property="deptName" column="dept_name"/>
</resultMap>
<!-- 通過 select 標簽進行查詢操作,這里查詢的是所有信息 -->
<select id="findAll" resultMap="deptMapper">
select * from dept
</select>
</mapper>
7. 測試運行
@org.junit.Test
public void test() {
SqlSession session = SqlSessionFactoryUtil.openSqlSession();
DeptMapper mapper = session.getMapper(DeptMapper.class);
List<Dept> depts = mapper.findAll();
for (Dept dept : depts) {
System.out.println(dept);
}
// 一定記得及時關閉 SqlSession 釋放資源
session.close();
}
以上記錄了mybatis最基本的操作狼讨,完整代碼見
https://github.com/zzz-tao/mybatis