文章目錄
MyBatista入門到入土——帶你走進Mybatis的世界
Hibernate
ORM
對象關係映射,就是將數據庫中的表和java中的對象建立映射,可以讓我們操作對象來間接的操作數據庫
Hibernate
可以通過java對象來間接的操作數據庫。java對象就相當於數據庫中表的代理一樣。
對於開發者來說就是隱藏了底層jdbc和db的交互過程。
- 優點
- 簡化jdbc操作
- 對於開發者來說不需要關心sql值需要取操作對象即可。
- 代碼移植性比較好,會自動自適應
- 開發效率高
- 缺點
- sql優化艱難,很難干預需要執行的sql
- 入門容易,進階難
- 對於複雜的動態sql,代碼需要很多判斷以及組裝,動態sql 這塊支持欠缺。
持久化
持久化是將程序數據在持久狀態和瞬時狀態間轉換的機制
- 即把數據(內存中的對象)保存到可永久保存的存儲設備中(磁盤)。
- 主要應用是將內存中的對象存儲在數據庫中,或者存儲在磁盤文件中、XML數據文件中
- JDBC就是一種持久化機制。文件IO也是一種持久化機制
作用——爲了解決內存本身的缺陷
- 內存斷電後數據會丟失
- 內存過於昂貴以及維護成本較高。
持久層
什麼是持久層
- 完成持久化工作的代碼塊—>dao層【DAO數據訪問對象】
- 大多數情況下特別是企業級應用,數據持久化往往也就意味着將內存中的數據保存到磁盤中,持久化的時間過長則大多數通過各種關係數據庫來完成
- 用來操作數據庫存在的
爲什麼需要MyBatista
- MyBatista就是進行數據和數據庫之間的交互
- 通過使用MyBatista框架可以減少重複代碼,提高開發效率
- MyBatista是一個半自動化的ORM框架(對象關係映射)
- MyBatista優點:
- 無侵入:只做增強不做改變,引入它不會對工程產生影響
- 損耗小:啓動即會自動注入基本的CURD,性能基本無消耗,直接面向對象操作
- 強大的CRUD:內置通用Mapper、通用Service。
- 支持Lambda形式調用:通過Lambda表達式,方便的編寫各種查詢條件。
- 支持主鍵自動生成:
- 解除sql和程序代碼的耦合:通過提供DAO層,將業務邏輯和數據訪問邏輯分離,便於維護
- 提供xml標籤,支持編寫動態sql
框架結構
Mybatis常用示例
思路:搭建環境——導入MyBatista——編寫代碼——測試
最後成品圖:
準備數據庫
/*創建數據庫zhonghubatis*/
DROP DATABASE IF EXISTS `zhonghubatis`;
CREATE DATABASE `zhonghubatis`;
USE `zhonghubatis`;
/*創建表結構*/
DROP TABLE IF EXISTS `zhonghu_user`;
CREATE TABLE zhonghu_user (
id BIGINT AUTO_INCREMENT PRIMARY KEY COMMENT '主鍵,用戶id,自動增長',
`name` VARCHAR(32) NOT NULL DEFAULT '' COMMENT '姓名',
`age` SMALLINT NOT NULL DEFAULT 1 COMMENT '年齡',
`salary` DECIMAL(12,2) NOT NULL DEFAULT 0 COMMENT '薪水'
) COMMENT '用戶表';
SELECT * FROM zhonghu_user;
首先我們先創建一個zhonghubatis數據庫,然後創建一個用戶表,其中包含四個字段,其中id爲自增長。
爲了演示mybatis我們這張表要滿足一下幾個條件
- 實現一個通用的插入操作:支持動態插入,可以更具傳入的字段的值,動態生成所需要的insert
- 批量插入功能
- 實現一個通用的更新操作:支持動態更新操作,可以根據傳入的字段,動態生成所需要的各種update語句
- 實現一個通用的查詢操作:支持各種組合條件查詢,支持排序、分頁、支持返回列控制等各種複雜的查詢操作
創建maven項目
創建一個maven項目以及一個子項目mybatis-01-hello如圖所示
引入mybatis依賴
在父maven文件中:
<?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.zhonghu</groupId>
<artifactId>zhonghuMabits</artifactId>
<packaging>pom</packaging>
<version>1.0-SNAPSHOT</version>
<modules>
<module>mybatis-01-hello</module>
</modules>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<!-- 配置maven編譯的時候採用的編譯器版本 -->
<maven.compiler.compilerVersion>1.8</maven.compiler.compilerVersion>
<!-- 指定源代碼是什麼版本的,如果源碼和這個版本不符將報錯,maven中執行編譯的時候會用到這個配置,默認是1.5,這個相當於javac命令後面的-source參數 -->
<maven.compiler.source>1.8</maven.compiler.source>
<!-- 該命令用於指定生成的class文件將保證和哪個版本的虛擬機進行兼容,maven中執行編譯的時候會用到這個配置,默認是1.5,這個相當於javac命令後面的-target參數 -->
<maven.compiler.target>1.8</maven.compiler.target>
</properties>
<dependencyManagement>
<dependencies>
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.5.2</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.20</version>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.18.12</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>ch.qos.logback</groupId>
<artifactId>logback-classic</artifactId>
<version>1.2.3</version>
</dependency>
</dependencies>
</dependencyManagement>
</project>
在mybatis-01-hello 中
<?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">
<parent>
<artifactId>zhonghuMabits</artifactId>
<groupId>com.zhonghu</groupId>
<version>1.0-SNAPSHOT</version>
</parent>
<modelVersion>4.0.0</modelVersion>
<artifactId>mybatis-01-hello</artifactId>
<dependencies>
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.5.2</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
</dependency>
<dependency>
<groupId>ch.qos.logback</groupId>
<artifactId>logback-classic</artifactId>
</dependency>
</dependencies>
</project>
這樣我們就引入了mybatis所需的包、mysql jdbc驅動、lombok(可以自動生成一些get、set方法)、單元測試需要的Junit包、日誌輸出所需的logback包。
配置logback
爲了在mybatis運行過程中查看日誌,諸如sql信息、sql參數、執行的結果等信息。
創建在子文件夾下的src/main/resources中新建logback.xml:
<?xml version="1.0" encoding="UTF-8"?>
<configuration>
<appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
<encoder>
<pattern>%d{mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n</pattern>
</encoder>
</appender>
<logger name="com.zhonghu" level="debug" additivity="false">
<appender-ref ref="STDOUT" />
</logger>
</configuration>
創建mybatis相關文件
user.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.zhonghu.mybatis.UserMapper">
<!-- 插入 -->
<insert id="insert" parameterType="com.zhonghu.mybatis.UserModel" keyProperty="id" useGeneratedKeys="true">
<![CDATA[ INSERT INTO `zhonghu_user` ]]>
<trim prefix="(" suffix=")" suffixOverrides=",">
<if test="id!=null">
<![CDATA[ `id`, ]]>
</if>
<if test="name!=null">
<![CDATA[ `name`, ]]>
</if>
<if test="age!=null">
<![CDATA[ `age`, ]]>
</if>
<if test="salary!=null">
<![CDATA[ `salary`, ]]>
</if>
</trim>
<![CDATA[ VALUES ]]>
<trim prefix="(" suffix=")" suffixOverrides=",">
<if test="id!=null">
<![CDATA[ #{id}, ]]>
</if>
<if test="name!=null">
<![CDATA[ #{name}, ]]>
</if>
<if test="age!=null">
<![CDATA[ #{age}, ]]>
</if>
<if test="salary!=null">
<![CDATA[ #{salary}, ]]>
</if>
</trim>
</insert>
<!-- 批量插入 -->
<insert id="insertBatch" parameterType="map">
<![CDATA[ INSERT INTO `zhonghu_user` (`id`, `name`, `age`, `salary`) VALUES ]]>
<foreach collection="list" separator="," item="item">
(#{item.id}, #{item.name}, #{item.age}, #{item.salary})
</foreach>
</insert>
<!-- 更新 -->
<update id="update" parameterType="com.zhonghu.mybatis.UserModel">
<![CDATA[ UPDATE `zhonghu_user` ]]>
<set>
<if test="name!=null">
<![CDATA[ `name` = #{name}, ]]>
</if>
<if test="age!=null">
<![CDATA[ `age` = #{age}, ]]>
</if>
<if test="salary!=null">
<![CDATA[ `salary` = #{salary}, ]]>
</if>
</set>
<where>
<if test="id!=null">
<![CDATA[ AND `id` = #{id} ]]>
</if>
</where>
</update>
<!-- 更新 -->
<update id="updateByMap" parameterType="map">
<![CDATA[ UPDATE `zhonghu_user` ]]>
<set>
<if test="name!=null">
<![CDATA[ `name` = #{name}, ]]>
</if>
<if test="age!=null">
<![CDATA[ `age` = #{age}, ]]>
</if>
<if test="salary!=null">
<![CDATA[ `salary` = #{salary}, ]]>
</if>
</set>
<where>
<if test="id!=null">
<![CDATA[ AND `id` = #{id} ]]>
</if>
</where>
</update>
<!-- 刪除 -->
<delete id="delete" parameterType="map">
<![CDATA[
DELETE FROM `zhonghu_user`
]]>
<where>
<if test="id!=null">
<![CDATA[ AND `id` = #{id} ]]>
</if>
</where>
</delete>
<!-- 查詢記錄 -->
<select id="getModelList" parameterType="map" resultType="com.zhonghu.mybatis.UserModel">
<![CDATA[
SELECT
]]>
<choose>
<when test="tableColumnList!=null and tableColumnList.size() >= 1">
<foreach collection="tableColumnList" item="item" separator=",">
<![CDATA[ ${item} ]]>
</foreach>
</when>
<otherwise>
<![CDATA[
`id`,
`name`,
`age`,
`salary`
]]>
</otherwise>
</choose>
<![CDATA[
FROM
`zhonghu_user` a
]]>
<where>
<if test="id!=null and id.toString()!=''">
<![CDATA[ AND a.`id` = #{id} ]]>
</if>
<if test="idList!=null and idList.size() >= 1">
<![CDATA[ AND a.`id` IN ]]>
<foreach collection="idList" item="item" open="(" separator="," close=")">
<![CDATA[ #{item} ]]>
</foreach>
</if>
<if test="name!=null and name.toString()!=''">
<![CDATA[ AND a.`name` = #{name} ]]>
</if>
<if test="age!=null and age.toString()!=''">
<![CDATA[ AND a.`age` = #{age} ]]>
</if>
<if test="salary!=null and salary.toString()!=''">
<![CDATA[ AND a.`salary` = #{salary} ]]>
</if>
<if test="nameLike!=null and nameLike.toString()!=''">
<![CDATA[ AND a.`name` like '%${nameLike}%' ]]>
</if>
<if test="salaryGte!=null and salaryGte.toString()!=''">
<![CDATA[ AND a.`salary` >= #{salaryGte} ]]>
</if>
</where>
<if test="sort!=null and sort.toString()!=''">
<![CDATA[ order by ${sort} ]]>
</if>
<if test="skip!=null and pageSize!=null">
<![CDATA[ LIMIT #{skip},#{pageSize} ]]>
</if>
</select>
</mapper>
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>
<property name="driver" value="com.mysql.jdbc.Driver"/>
<property name="url" value="jdbc:mysql://localhost:3306/zhonghubatis?useUnicode=true&characterEncoding=utf-8&serverTimezone=GMT"/>
<property name="username" value="root"/>
<property name="password" value="123456"/>
</properties>
<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>
<mappers>
<mapper resource="mapper/user.xml"/>
</mappers>
</configuration>
注意數據庫連接中的url 因爲mysql是8.0版本的,所以需要添加時區用& amp;來連接
UserMapper接口
package com.zhonghu.mybatis;
import java.util.List;
import java.util.Map;
/**
* Created with IntelliJ IDEA
* Description:
* Author: sun mingzhi
* Date: 2020/6/3 11:17
* Company: Inspur
*/
public interface UserMapper {
// 插入用戶信息
void insert(UserModel userModel);
// 批量插入用戶信息
void insertBatch(List<UserModel> userModelList);
// 更新用戶記錄
int update(UserModel userModel);
// 通過map來更新用戶記錄
int updateByMap(Map<String,Object>map);
// 通過map來刪除用戶記錄
int delete(Map<String,Object>map);
// 查詢用戶列表
List<UserModel> getModelList(Map<String,Object>map);
}
UserModel類
package com.zhonghu.mybatis;
import lombok.*;
/**
* Created with IntelliJ IDEA
* Description:
* Author: sun mingzhi
* Date: 2020/6/3 11:22
* Company: Inspur
*/
@Getter
@Setter
@NoArgsConstructor
@AllArgsConstructor
@Builder
@ToString
public class UserModel {
private Long id;
private String name;
private Integer age;
private Double salary;
}
在其中使用了很多lombak註解,通過這些註解,lombak可以幫助我們自動生成上面字段的get、set方法,無參構造方法,有參構造方法、builder模式構件對象代碼、重寫toString方法。
這些都在代碼編譯爲字節碼前寫進去。
UserUtile類
package com.zhonghu.mybatis;
import lombok.extern.slf4j.Slf4j;
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;
/**
* Created with IntelliJ IDEA
* Description:
* Author: sun mingzhi
* Date: 2020/6/3 13:56
* Company: Inspur
*/
@Slf4j
public class UserUtil {
private static SqlSessionFactory sqlSessionFactory = build();
public static SqlSessionFactory build(){
try{
return new SqlSessionFactoryBuilder().build(Resources.getResourceAsStream("mybatis-config.xml"));
}catch (IOException e){
log.error(e.getMessage(),e);
throw new RuntimeException(e);
}
}
@FunctionalInterface
public interface SessionCall<O>{
O call(SqlSession session) throws Exception;
}
@FunctionalInterface
public interface MapperCall<T,O>{
O call(T mapper)throws Exception;
}
public static <T, O> O callMapper(Class<T> tClass,MapperCall<T,O> mapperCall) throws Exception{
return call(session-> mapperCall.call(session.getMapper(tClass)));
}
public static <O> O call(SessionCall<O> sessionCall)throws Exception{
try(SqlSession session = sqlSessionFactory.openSession(true);){
return sessionCall.call(session);
}
}
}
創建單元測試類UserMapperTest
UserMapperTest
package com.zhonghu.mybatis;
import lombok.extern.slf4j.Slf4j;
import org.junit.Test;
import java.util.*;
import java.util.stream.Collectors;
/**
* Created with IntelliJ IDEA
* Description:
* Author: sun mingzhi
* Date: 2020/6/3 14:14
* Company: Inspur
*/
@Slf4j
public class UserMapperTest {
//動態插入
@Test
public void insert() throws Exception {
UserModel userModel1 = UserModel.builder().name("冢狐java").build();
UserUtil.callMapper(UserMapper.class, mapper -> {
mapper.insert(userModel1);
return null;
});
log.info("插入結果:{}", this.getModelById(userModel1.getId()));
log.info("---------------------");
UserModel userModel2 = UserModel.builder().name("冢狐").age(18).salary(10000.0).build();
UserUtil.callMapper(UserMapper.class, mapper -> {
mapper.insert(userModel2);
return null;
});
log.info("插入結果:{}", this.getModelById(userModel2.getId()));
}
//批量插入
@Test
public void insertBatch() throws Exception {
List<UserModel> userModelList = new ArrayList<>();
for (int i = 1; i <= 5; i++) {
userModelList.add(UserModel.builder().name("冢狐java-" + i).age(30 + i).salary(10000.00 * i).build());
userModelList.add(UserModel.builder().name("Mybatis-" + i).age(30 + i).salary(10000.00 * i).build());
}
UserUtil.callMapper(UserMapper.class, mapper -> {
mapper.insertBatch(userModelList);
return null;
});
List<UserModel> userModelList1 = UserUtil.callMapper(UserMapper.class, mapper -> mapper.getModelList(null));
log.info("結果:{}", userModelList1);
}
//根據用戶id刪除數據
@Test
public void delete() throws Exception {
Map<String, Object> map = new HashMap<>();
//需要刪除的用戶id
map.put("id", 1);
Integer count = UserUtil.callMapper(UserMapper.class, mapper -> mapper.delete(map));
log.info("刪除行數:{}", count);
}
//動態更新
@Test
public void update() throws Exception {
//將userId=10的name修改爲:修改測試者
Long userId1 = 10L;
Integer count = UserUtil.callMapper(UserMapper.class, mapper -> mapper.update(UserModel.builder().id(userId1).name("修改測試者").build()));
log.info("更新行數:{}", count);
log.info("---------------------");
//將userId=3的name修改爲:修改測試者2,薪水爲:1234.56
Long userId2 = 11L;
count = UserUtil.callMapper(UserMapper.class, mapper -> mapper.update(UserModel.builder().id(userId2).name("修改測試者2").salary(1234.56D).build()));
log.info("更新行數:{}", count);
}
//按用戶id查詢
public UserModel getModelById(Long userId) throws Exception {
//查詢指定id的數據
Map<String, Object> map = new HashMap<>();
map.put("id", userId);
return UserUtil.callMapper(UserMapper.class, mapper -> {
List<UserModel> userModelList = mapper.getModelList(map);
if (userModelList.size() == 1) {
return userModelList.get(0);
}
return null;
});
}
//查詢所有數據
@Test
public void getModelList1() throws Exception {
List<UserModel> userModelList = UserUtil.callMapper(UserMapper.class, mapper -> mapper.getModelList(null));
log.info("結果:{}", userModelList);
}
//查詢多個用戶id對應的數據
@Test
public void getModelListByIds() throws Exception {
List<Integer> idList = Arrays.asList(2, 3, 4).stream().collect(Collectors.toList());
Map<String, Object> map = new HashMap<>();
map.put("idList", idList);
List<UserModel> userModelList = UserUtil.callMapper(UserMapper.class, mapper -> mapper.getModelList(map));
log.info("結果:{}", userModelList);
}
//多條件 & 指定返回的列
@Test
public void getModelList2() throws Exception {
//查詢姓名中包含冢狐java以及薪資大於1萬的用戶id、姓名
Map<String, Object> map = new HashMap<>();
map.put("nameLike", "冢狐java");
map.put("salaryGte", 10000.00D);
//需要返回的列
List<String> tableColumnList = new ArrayList<>();
tableColumnList.add("id");
tableColumnList.add("name");
map.put("tableColumnList", tableColumnList);
List<UserModel> userModelList = UserUtil.callMapper(UserMapper.class, mapper -> mapper.getModelList(map));
log.info("結果:{}", userModelList);
}
//條件過濾 & 排序 & 分頁查詢數據 & 只返回用戶id、salary
@Test
public void getPage() throws Exception {
//查詢姓名中包含冢狐java以及薪資大於1萬的用戶id,按照薪資倒敘,每頁5條取第1頁
Map<String, Object> map = new HashMap<>();
map.put("nameLike", "冢狐java");
map.put("salaryGte", 10000.00D);
//加入排序參數
map.put("sort", "salary desc");
//加入分頁參數
int page = 1;
int pageSize = 5;
map.put("skip", (page - 1) * pageSize);
map.put("pageSize", pageSize);
//加入需要返回的列
List<String> tableColumnList = new ArrayList<>();
tableColumnList.add("id");
tableColumnList.add("salary");
map.put("tableColumnList", tableColumnList);
List<UserModel> userModelList = UserUtil.callMapper(UserMapper.class, mapper -> mapper.getModelList(map));
log.info("結果:{}", userModelList);
}
}
運行結果
數據庫信息
用例分析
insert方法:
- 代碼
//動態插入
@Test
public void insert() throws Exception {
UserModel userModel1 = UserModel.builder().name("冢狐java").build();
UserUtil.callMapper(UserMapper.class, mapper -> {
mapper.insert(userModel1);
return null;
});
log.info("插入結果:{}", this.getModelById(userModel1.getId()));
log.info("---------------------");
UserModel userModel2 = UserModel.builder().name("冢狐").age(18).salary(10000.0).build();
UserUtil.callMapper(UserMapper.class, mapper -> {
mapper.insert(userModel2);
return null;
});
log.info("插入結果:{}", this.getModelById(userModel2.getId()));
}
- 結果日誌
主要操作
- 插入一條用戶記錄,只有name字段有值
- 去db中查詢步驟1中插入的記錄
- 插入一條用戶記錄,這次插入的記錄所有字段都指定了值
- 去db中查詢步驟3插入的記錄
兩次插入的字段的值不一樣,因此產生的sql也不一樣,是因爲mapper.insert方法可以根據UserModel對象字段是否有值來組裝我們西藥的sql,即動態插入
案例總結
上面這些用例,基本能包含我們對db所需的大部分操作,動態sql處理方面體現的最爲強力。
其中文件:user.xml是這個mybatis中的核心文件,我們需要寫的sql以及判斷邏輯基本都在這個xml中。