日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪(fǎng)問(wèn) 生活随笔!

生活随笔

當(dāng)前位置: 首頁(yè) > 编程资源 > 编程问答 >内容正文

编程问答

【SSM框架】MyBatis

發(fā)布時(shí)間:2023/12/20 编程问答 32 豆豆
生活随笔 收集整理的這篇文章主要介紹了 【SSM框架】MyBatis 小編覺(jué)得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.

MyBatis

  • 1、簡(jiǎn)介
    • 1.1、什么是MyBatis
    • 1.2、持久化
    • 1.3、持久層
    • 1.4、為什么需要MyBatis
  • 2、第一個(gè)MyBatis程序
    • 2.1、搭建環(huán)境
    • 2.2、創(chuàng)建一個(gè)模塊
    • 2.3、編寫(xiě)代碼
    • 2.4、測(cè)試
  • 3、CRUD
    • 1、namespace
    • 2、編寫(xiě)接口
    • 3、編寫(xiě)接口對(duì)應(yīng)的mapper中的語(yǔ)句
    • 4、測(cè)試
    • 5、注意點(diǎn)
    • 6、萬(wàn)能map
    • 7、模糊查詢(xún)
  • 4、配置解析
    • 1、核心配置文件
    • 2、環(huán)境配置(environments)
    • 3、屬性(properties)
    • 4、類(lèi)型別名(typeAliases)
    • 5、設(shè)置(settings)
    • 6、其他配置
    • 7、映射器(mappers)
    • 8、生命周期和作用域
        • SqlSessionFactoryBuilder
        • SqlSessionFactory
        • SqlSession
  • 5、解決屬性名和字段名不一致的問(wèn)題
    • 1、問(wèn)題
    • 2、resultMap
  • 6、日志
    • 6.1、日志工廠(chǎng)
    • 6.2、Log4J
  • 7、分頁(yè)
    • 7.1、使用limit分頁(yè)
    • 7.2、RowBounds分頁(yè)
    • 7.3、分頁(yè)插件
  • 8、使用注解開(kāi)發(fā)
    • 8.1、面向接口編程
    • 8.2、使用注解開(kāi)發(fā)
    • 8.3、CRUD
  • 9、Lombok
  • 10、多對(duì)一處理
    • 測(cè)試環(huán)境搭建
    • 按照查詢(xún)嵌套處理
    • 按照結(jié)果嵌套處理
  • 11、一對(duì)多處理
    • 環(huán)境搭建
    • 按照結(jié)果嵌套處理
    • 按照查詢(xún)嵌套處理
    • 小結(jié)
    • 注意點(diǎn)
  • 12、動(dòng)態(tài)SQL
    • 搭建環(huán)境
    • if
    • choose (when, otherwise)
    • trim (where, set)
    • SQL片段
    • foreach
  • 13、緩存
    • 13.1、簡(jiǎn)介
    • 13.2、mybatis緩存
    • 13.3、一級(jí)緩存
    • 13.4、二級(jí)緩存
    • 13.5、緩存原理
    • 13.6、自定義緩存-ehcache

SMM框架 好的學(xué)習(xí)方式:看官方文檔

1、簡(jiǎn)介

1.1、什么是MyBatis

  • MyBatis 是一款優(yōu)秀的持久層框架
  • 它支持自定義 SQL、存儲(chǔ)過(guò)程以及高級(jí)映射。
  • MyBatis 免除了幾乎所有的 JDBC 代碼以及設(shè)置參數(shù)和獲取結(jié)果集的工作。
  • MyBatis 可以通過(guò)簡(jiǎn)單的 XML 或注解來(lái)配置和映射原始類(lèi)型、接口和 Java POJO(Plain Old Java Objects,普通老式 Java 對(duì)象)為數(shù)據(jù)庫(kù)中的記錄。
  • MyBatis本是apache的一個(gè)開(kāi)源項(xiàng)目iBatis,2010年這個(gè)項(xiàng)目且改名為MyBatis。
  • 2013年11月遷移到Github。

如何獲得Mybatis

  • maven倉(cāng)庫(kù)

    <!-- https://mvnrepository.com/artifact/org.mybatis/mybatis --> <dependency><groupId>org.mybatis</groupId><artifactId>mybatis</artifactId><version>3.5.7</version> </dependency>
  • github:https://github.com/mybatis/mybatis-3/releases

  • 中文文檔:https://mybatis.org/mybatis-3/zh/index.html

1.2、持久化

數(shù)據(jù)持久化

  • 持久化就是將程序的數(shù)據(jù)在持久狀態(tài)和瞬時(shí)狀態(tài)轉(zhuǎn)化的過(guò)程
  • 內(nèi)存:斷電即失
  • 數(shù)據(jù)庫(kù)(jdbc),io文件持久化

為什么需要持久化?

  • 有一些對(duì)象,不能讓它丟失
  • 內(nèi)存太貴

1.3、持久層

dao層 server層 controller層

  • 完成持久化工作的代碼塊
  • 層界限十分明顯

1.4、為什么需要MyBatis

  • 幫忙程序員將數(shù)據(jù)存入到數(shù)據(jù)庫(kù)中
  • 傳統(tǒng)的jdbc太復(fù)雜了。簡(jiǎn)化。框架。自動(dòng)化。
  • 優(yōu)點(diǎn):
    • 簡(jiǎn)單易學(xué)
    • 靈活
    • sql和代碼的分離,提高了可維護(hù)性。
    • 提供映射標(biāo)簽,支持對(duì)象與數(shù)據(jù)庫(kù)的orm字段關(guān)系映射
    • 提供對(duì)象關(guān)系映射標(biāo)簽,支持對(duì)象關(guān)系組建維護(hù)
    • 提供xml標(biāo)簽,支持編寫(xiě)動(dòng)態(tài)sql
  • 最重要的一點(diǎn):使用的人多!

2、第一個(gè)MyBatis程序

思路:搭建環(huán)境–>導(dǎo)入Mybatis–>編寫(xiě)代碼–>測(cè)試

2.1、搭建環(huán)境

搭建數(shù)據(jù)庫(kù)

CREATE DATABASE `mybatis`;USE `mybatis`;CREATE TABLE `user`(`id` INT(20) NOT NULL PRIMARY KEY,`name` VARCHAR(30) DEFAULT NULL,`pwd` VARCHAR(30) DEFAULT NULL ) ENGINE=INNODB DEFAULT CHARSET=utf8;INSERT INTO `user`(`id`,`name`,`pwd`) VALUES (1,'zyy','123456'), (2,'張三','123456'), (3,'李四','123456');

新建項(xiàng)目

  • 新建一個(gè)普通的maven項(xiàng)目

  • 刪除src目錄(作為父工程)

  • 導(dǎo)入maven依賴(lài)

    <!-- 導(dǎo)入依賴(lài) --><dependencies><!-- MySQL --><dependency><groupId>mysql</groupId><artifactId>mysql-connector-java</artifactId><version>8.0.30</version></dependency><!-- MyBatis --><dependency><groupId>org.mybatis</groupId><artifactId>mybatis</artifactId><version>3.5.7</version></dependency><!-- juint --><dependency><groupId>junit</groupId><artifactId>junit</artifactId><version>4.12</version></dependency></dependencies>
  • 2.2、創(chuàng)建一個(gè)模塊

    • 編寫(xiě)mybatis的核心配置文件

      <?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE configurationPUBLIC "-//mybatis.org//DTD Config 3.0//EN""http://mybatis.org/dtd/mybatis-3-config.dtd"> <!--configuration 核心配置文件--> <configuration><!-- environment 元素體中包含了事務(wù)管理和連接池的配置--><environments default="development"><environment id="development"><transactionManager type="JDBC"/><dataSource type="POOLED"><property name="driver" value="${com.mysql.cj.jdbc.Driver}"/><property name="url" value="${jdbc:mysql://localhost:3306/mybatis?useUnicode=true&amp;characterEncoding=utf-8&amp;useSSL=true&amp;serverTimezone=GMT%2B8}"/><property name="username" value="${root}"/><property name="password" value="${123456}"/></dataSource></environment></environments><!-- mappers 元素則包含了一組映射器(mapper),這些映射器的 XML 映射文件包含了 SQL 代碼和映射定義信息。--><!-- 每一個(gè)Mapper.xml都需要在mybatis核心配置文件中注冊(cè) --></configuration>
    • 編寫(xiě)mybatis工具類(lèi)

      package com.sue.utils;import org.apache.ibatis.io.Resources; import org.apache.ibatis.jdbc.SQL; 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 with IntelliJ IDEA.** @author : Genius Sue* @version : 1.0* @Project : Mybatis-Study* @Package : com.sue.utils* @ClassName : .java* @createTime : 2022/9/7 15:20* @Email : 1420779618@qq.com* @公眾號(hào) :* @Website :* @Description :*/ //工具類(lèi)SqlSessionFactory-->SqlSession public class MybatisUtil {private static SqlSessionFactory sqlSessionFactory;static {String resource = "mybatis-config.xml";try {//使用Mybatis第一步:獲取SqlSessionFactory對(duì)象InputStream inputStream = Resources.getResourceAsStream(resource);sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);} catch (IOException e) {throw new RuntimeException(e);}}// 既然有了 SqlSessionFactory,顧名思義,我們可以從中獲得 SqlSession 的實(shí)例。// SqlSession 提供了在數(shù)據(jù)庫(kù)執(zhí)行 org.apache.ibatis.jdbc.SQL 命令所需的所有方法。public static SqlSession getSqlSession(){return sqlSessionFactory.openSession();} }

    2.3、編寫(xiě)代碼

    • 實(shí)體類(lèi)

      package com.sue.pojo;/*** Created with IntelliJ IDEA.** @author : Genius Sue* @version : 1.0* @Project : Mybatis-Study* @Package : com.sue.pojo* @ClassName : .java* @createTime : 2022/9/7 15:29* @Email : 1420779618@qq.com* @公眾號(hào) :* @Website :* @Description :*/ public class User {private int id;private String name;private String pwd;public User() {}public User(int id, String name, String pwd) {this.id = id;this.name = name;this.pwd = pwd;}public int getId() {return id;}public void setId(int id) {this.id = id;}public String getName() {return name;}public void setName(String name) {this.name = name;}public String getPwd() {return pwd;}public void setPwd(String pwd) {this.pwd = pwd;}@Overridepublic String toString() {return "User{" +"id=" + id +", name='" + name + '\'' +", p wd='" + pwd + '\'' +'}';} }
    • Dao接口

      package com.sue.dao;import com.sue.pojo.User;import java.util.List;/*** Created with IntelliJ IDEA.** @author : Genius Sue* @version : 1.0* @Project : Mybatis-Study* @Package : com.sue.dao* @ClassName : .java* @createTime : 2022/9/7 15:31* @Email : 1420779618@qq.com* @公眾號(hào) :* @Website :* @Description :*/ public interface UserDao {List<User> getUserList(); }
    • 接口實(shí)現(xiàn)類(lèi)(由原來(lái)的UserDaoImpl轉(zhuǎn)為一個(gè)Mapper配置文件)

      <?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE mapperPUBLIC "-//mybatis.org//DTD Mapper 3.0//EN""http://mybatis.org/dtd/mybatis-3-mapper.dtd"> <!--namespace=綁定一個(gè)對(duì)應(yīng)的DAO/Mapper接口--> <mapper namespace="com.sue.dao.UserDao"><!-- id就是方法的名字 --><select id="getUserList" resultType="com.sue.pojo.User">select *from mybatis.user;</select></mapper>

    2.4、測(cè)試

    注意點(diǎn):

    org.apache.ibatis.binding.BindingException: Type interface com.sue.dao.UserDao is not known to the MapperRegistry.

    [外鏈圖片轉(zhuǎn)存失敗,源站可能有防盜鏈機(jī)制,建議將圖片保存下來(lái)直接上傳(img-WnNA5Wf1-1662864948627)(C:\Users\Genius Sue\AppData\Roaming\Typora\typora-user-images\image-20220907155016783.png)]

    Caused by: java.io.IOException: Could not find resource com/zyy/dao/UserMapper.xml

    pom改成:

    <?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.sue</groupId><artifactId>Mybatis-Study</artifactId><packaging>pom</packaging><version>1.0-SNAPSHOT</version><modules><module>mybatis-01</module></modules><!-- 導(dǎo)入依賴(lài) --><dependencies><!-- MySQL --><dependency><groupId>mysql</groupId><artifactId>mysql-connector-java</artifactId><version>8.0.30</version></dependency><!-- MyBatis --><dependency><groupId>org.mybatis</groupId><artifactId>mybatis</artifactId><version>3.5.7</version></dependency><!-- juint --><dependency><groupId>junit</groupId><artifactId>junit</artifactId><version>4.12</version></dependency></dependencies><properties><maven.compiler.source>8</maven.compiler.source><maven.compiler.target>8</maven.compiler.target><project.build.sourceEncoding>UTF-8</project.build.sourceEncoding></properties><!--在build中配置resources,來(lái)防止我們資源導(dǎo)出失敗的問(wèn)題--><build><resources><resource><directory>src/main/resources</directory><includes><include>**/*.properties</include><include>**/*.xml</include></includes><filtering>false</filtering></resource><resource><directory>src/main/java</directory><includes><include>**/*.properties</include><include>**/*.xml</include></includes><filtering>false</filtering></resource></resources></build></project>

    核心配置文件中注冊(cè)mappers

    • junit測(cè)試

      package com.sue.dao;import com.sue.pojo.User; import com.sue.utils.MybatisUtil; import org.apache.ibatis.session.SqlSession; import org.junit.Test;import java.util.List;/*** Created with IntelliJ IDEA.** @author : Genius Sue* @version : 1.0* @Project : Mybatis-Study* @Package : com.sue.dao* @ClassName : .java* @createTime : 2022/9/7 15:45* @Email : 1420779618@qq.com* @公眾號(hào) :* @Website :* @Description :*/ public class UserDaoTest { // 最好將映射器放在方法作用域內(nèi)@Testpublic void test(){SqlSession sqlSession = MybatisUtil.getSqlSession();try {UserDao mapper = sqlSession.getMapper(UserDao.class);List<User> userList = mapper.getUserList();for (User user : userList) {System.out.println(user);}}finally {sqlSession.close();}// //獲得 SqlSession 對(duì)象 // SqlSession sqlSession = MybatisUtil.getSqlSession(); // // //執(zhí)行SQL // UserDao mapper = sqlSession.getMapper(UserDao.class); // List<User> userList = mapper.getUserList(); // // for (User user : userList) { // System.out.println(user); // } // // //關(guān)閉SqlSession // sqlSession.close();} }

    3、CRUD

    1、namespace

    namespace中的包名要和dao/mapper接口的包名一致

    選擇,查詢(xún)語(yǔ)句:

    • id :就是對(duì)應(yīng)的namespace中的方法名字
    • resultType:sql語(yǔ)句執(zhí)行的返回值類(lèi)型
    • parameterType:參數(shù)類(lèi)型

    2、編寫(xiě)接口

    package com.sue.dao;import com.sue.pojo.User;import java.util.List;/*** Created with IntelliJ IDEA.** @author : Genius Sue* @version : 1.0* @Project : Mybatis-Study* @Package : com.sue.dao* @ClassName : .java* @createTime : 2022/9/7 15:31* @Email : 1420779618@qq.com* @公眾號(hào) :* @Website :* @Description :*/ public interface UserMapper {//查詢(xún)所有用戶(hù)List<User> getUserList();//根據(jù)ID查詢(xún)用戶(hù)User getUserById(int id);//插入一個(gè)用戶(hù)int addUser(User user);//修改用戶(hù)int updateUser(User user);//刪除一個(gè)用戶(hù)int deleteUser(int id);}

    3、編寫(xiě)接口對(duì)應(yīng)的mapper中的語(yǔ)句

    <?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE mapperPUBLIC "-//mybatis.org//DTD Mapper 3.0//EN""http://mybatis.org/dtd/mybatis-3-mapper.dtd"> <!--namespace=綁定一個(gè)對(duì)應(yīng)的DAO/Mapper接口--> <mapper namespace="com.sue.dao.UserMapper"><!-- id就是方法的名字 --><select id="getUserList" resultType="com.sue.pojo.User">select *from mybatis.user;</select><select id="getUserById" parameterType="int" resultType="com.sue.pojo.User">select *from mybatis.userwhere id=#{id};</select><!-- 對(duì)象中的屬性可以直接取出來(lái) --><insert id="addUser" parameterType="com.sue.pojo.User">insert into mybatis.user (id,name,pwd) values(#{id},#{name},#{pwd})</insert><update id="updateUser" parameterType="com.sue.pojo.User">update mybatis.userset name = #{name},pwd=#{pwd}where id = #{id};</update><delete id="deleteUser" parameterType="int">delete from mybatis.userwhere id = #{id};</delete></mapper>

    4、測(cè)試

    package com.sue.dao;import com.sue.pojo.User; import com.sue.utils.MybatisUtil; import org.apache.ibatis.session.SqlSession; import org.junit.Test;import java.util.List;/*** Created with IntelliJ IDEA.** @author : Genius Sue* @version : 1.0* @Project : Mybatis-Study* @Package : com.sue.dao* @ClassName : .java* @createTime : 2022/9/7 15:45* @Email : 1420779618@qq.com* @公眾號(hào) :* @Website :* @Description :*/ public class UserMapperTest {@Testpublic void test(){//獲得 SqlSession 對(duì)象SqlSession sqlSession = MybatisUtil.getSqlSession();try {UserMapper mapper = sqlSession.getMapper(UserMapper.class);//執(zhí)行SQLList<User> userList = mapper.getUserList();for (User user : userList) {System.out.println(user);}}finally {//關(guān)閉SqlSessionsqlSession.close();}}@Testpublic void getUserById(){SqlSession sqlSession = MybatisUtil.getSqlSession();try {UserMapper mapper = sqlSession.getMapper(UserMapper.class);User userById = mapper.getUserById(2);System.out.println(userById);}finally {sqlSession.close();}}//增刪改需要提交事物@Testpublic void addUser(){SqlSession sqlSession = MybatisUtil.getSqlSession();try {UserMapper mapper = sqlSession.getMapper(UserMapper.class);mapper.addUser(new User(5,"Genius Sue","123456"));System.out.println("插入成功");//提交事物sqlSession.commit();}finally {sqlSession.close();}}@Testpublic void updateUser(){SqlSession sqlSession = MybatisUtil.getSqlSession();try {UserMapper mapper = sqlSession.getMapper(UserMapper.class);mapper.updateUser(new User(4,"Genius","123456"));//提交事物sqlSession.commit();System.out.println("更新成功");}finally {sqlSession.close();}}@Testpublic void deleteUser(){SqlSession sqlSession = null;try {sqlSession = MybatisUtil.getSqlSession();UserMapper mapper = sqlSession.getMapper(UserMapper.class);mapper.deleteUser(5);//提交事物sqlSession.commit();System.out.println("刪除成功");}finally {if (sqlSession!=null){sqlSession.close();}}}}

    5、注意點(diǎn)

    • 增刪改需要提交事務(wù)才會(huì)生效

    • 標(biāo)簽不要匹配錯(cuò)!

    • resource綁定mapper,需要使用路徑 .

    • 程序配置文件必須符合規(guī)范!

    • NullPointerException,沒(méi)有注冊(cè)到資源

    • 輸出的xml文件中存在中文亂碼問(wèn)題,更改編碼UTF-8

    • maven資源沒(méi)有導(dǎo)出問(wèn)題

    6、萬(wàn)能map

    假設(shè),我們的實(shí)例類(lèi),或者數(shù)據(jù)庫(kù)中的表,字段或者參數(shù)過(guò)多,我們應(yīng)該考慮使用map

    接口

    int addUser2(Map<String, Object> map);

    mapper

    <insert id="addUser2" parameterType="map">insert into `user`(id, name, pwd) values (#{userId},#{userName},#{password}) </insert>

    測(cè)試

    @Testpublic void addUser2() {SqlSession sqlSession = null;try {Map<String, Object> map = new HashMap<>();map.put("userId", 5);map.put("userName", "GCD");map.put("password", "123456");sqlSession = MybatisUtils.getSqlSession();UserMapper userMapper = sqlSession.getMapper(UserMapper.class);int num = userMapper.addUser2(map);if (num > 0) {System.out.println("插入成功!");}sqlSession.commit();} finally {if (sqlSession != null) {sqlSession.close();}}}

    Map傳遞參數(shù),直接在sql中取出key即可!

    對(duì)象傳遞參數(shù),直接在sql中取對(duì)象的屬性即可!

    只有一個(gè)基本類(lèi)型的情況下,可以直接在sql中取到!

    多個(gè)參數(shù)用Map,或者注解!

    7、模糊查詢(xún)

  • java代碼執(zhí)行的時(shí)候,傳遞通配符%

    List<User> userList = userMapper.getUserLike("%李%");
  • 在sql中拼接使用通配符 (不推薦,容易引起sql注入問(wèn)題)

    <!-- select id, name, pwd from `user` where id = ? --><!-- select id, name, pwd from `user` where id = 1 一般情況--><!-- select id, name, pwd from `user` where id = 1 or 1=1 sql注入情況--><select id="getUserLike" resultType="com.zyy.pojo.User" parameterType="string">select id, name, pwd from `user` where name like "%"#{value}"%"</select>
  • 4、配置解析

    1、核心配置文件

    • mybatis-config.xml

    • MyBatis 的配置文件包含了會(huì)深深影響 MyBatis 行為的設(shè)置和屬性信息。 配置文檔的頂層結(jié)構(gòu)如下:

    • configuration(配置)

      • [properties(屬性)]
      • [settings(設(shè)置)]
      • [typeAliases(類(lèi)型別名)]
      • [typeHandlers(類(lèi)型處理器)]
      • [objectFactory(對(duì)象工廠(chǎng))]
      • [plugins(插件)]
      • environments(環(huán)境配置)
        • environment(環(huán)境變量)
          • transactionManager(事務(wù)管理器)
          • dataSource(數(shù)據(jù)源)
      • [databaseIdProvider(數(shù)據(jù)庫(kù)廠(chǎng)商標(biāo)識(shí))]
      • [mappers(映射器)]

    2、環(huán)境配置(environments)

    MyBatis 可以配置成適應(yīng)多種環(huán)境

    不過(guò)要記住:盡管可以配置多個(gè)環(huán)境,但每個(gè) SqlSessionFactory 實(shí)例只能選擇一種環(huán)境。

    學(xué)會(huì)使用配置多套運(yùn)行環(huán)境!

    事務(wù)管理器(transactionManager)

    在 MyBatis 中有兩種類(lèi)型的事務(wù)管理器(也就是 type=“[JDBC|MANAGED]”):

    數(shù)據(jù)源(dataSource)

    有三種內(nèi)建的數(shù)據(jù)源類(lèi)型(也就是 type=“[UNPOOLED|POOLED|JNDI]”):

    MyBatis默認(rèn)的事務(wù)管理器就是JDBC,連接池:POOLED

    3、屬性(properties)

    我們可以通過(guò)properties屬性來(lái)實(shí)現(xiàn)引用配置文件

    這些屬性可以在外部進(jìn)行配置,并可以進(jìn)行動(dòng)態(tài)替換。你既可以在典型的 Java 屬性文件中配置這些屬性,也可以在 properties 元素的子元素中設(shè)置。【db.properties】

    在xml中,所有的標(biāo)簽都可以規(guī)定其順序

    編寫(xiě)一個(gè)配置文件

    db.properties

    driver = com.mysql.cj.jdbc.Driver url = jdbc:mysql://localhost:3306/mybatis?useUnicode=true&characterEncoding=utf-8&useSSL=true&serverTimezone=GMT%2B8 username = root password =123456

    在核心配置文件中引入

    <properties resource="db.properties"><property name="username" value="root"/><property name="password" value="123456"/></properties>
    • 可以直接引入外部文件
    • 可以在其中增加一些屬性配置
    • 如果兩個(gè)文件有同一個(gè)字段,優(yōu)先使用外部配置文件的!

    4、類(lèi)型別名(typeAliases)

    • 類(lèi)型別名可為 Java 類(lèi)型設(shè)置一個(gè)縮寫(xiě)名字。
    • 意在降低冗余的全限定類(lèi)名書(shū)寫(xiě)。
    <typeAliases><typeAlias type="com.sue.pojo.User" alias="User"/> </typeAliases>

    也可以指定一個(gè)包名,MyBatis 會(huì)在包名下面搜索需要的 Java Bean

    掃描實(shí)體類(lèi)的包,它的默認(rèn)別名就是這個(gè)類(lèi)的類(lèi)名,首字母小寫(xiě)。

    <!-- 可以給實(shí)體類(lèi)取別名 --> <typeAliases><package name="com.sue.pojo"/> </typeAliases>

    在實(shí)體類(lèi)比較少的時(shí)候,使用第一種方式。

    如果實(shí)體類(lèi)比較多,建議使用第二種。

    第一種可以自定義別名,第二種不行,如果非要改的話(huà),需要在實(shí)體上增加注解

    @Alias("user") public class User {}

    5、設(shè)置(settings)

    這是 MyBatis 中極為重要的調(diào)整設(shè)置,它們會(huì)改變 MyBatis 的運(yùn)行時(shí)行為。

    6、其他配置

    • typeHandlers(類(lèi)型處理器)
    • objectFactory(對(duì)象工廠(chǎng))
    • plugins(插件)
      • mybatis-generator-core
      • mybatis-plus
      • 通用mapper

    7、映射器(mappers)

    MapperRegistry:注冊(cè)綁定我們的mapper文件

    方式一:

    <!-- 每一個(gè)Mapper.xml都需要在mybatis核心配置文件中注冊(cè) --> <mappers><mapper resource="com/sue/dao/UserMapper.xml"/> </mappers>

    方式二:使用class文件綁定注冊(cè)

    <mappers><mapper class="com.sue.dao.UserMapper"/> </mappers>

    注意點(diǎn):

    • 接口和它的Mapper配置文件必須同名!
    • 接口和它的Mapper配置文件必須在同一個(gè)包下!

    方式三:使用掃描包進(jìn)行注入綁定

    <mappers><package name="com.sue.dao"/> </mappers>

    注意點(diǎn):

    • 接口和它的Mapper配置文件必須同名!
    • 接口和它的Mapper配置文件必須在同一個(gè)包下!

    8、生命周期和作用域

    生命周期和作用域類(lèi)別是至關(guān)重要的,因?yàn)殄e(cuò)誤的使用會(huì)導(dǎo)致非常嚴(yán)重的并發(fā)問(wèn)題

    SqlSessionFactoryBuilder

    • 一旦創(chuàng)建了 SqlSessionFactory,就不再需要它了
    • 局部變量

    SqlSessionFactory

    • 說(shuō)白了就是可以想象為:數(shù)據(jù)庫(kù)連接池
    • 一旦被創(chuàng)建就應(yīng)該在應(yīng)用的運(yùn)行期間一直存在,沒(méi)有任何理由丟棄它或重新創(chuàng)建另一個(gè)實(shí)例。
    • SqlSessionFactory 的最佳作用域是應(yīng)用作用域
    • 最簡(jiǎn)單的就是使用單例模式或者靜態(tài)單例模式。

    SqlSession

    • 連接到連接池的一個(gè)請(qǐng)求

    • 每個(gè)線(xiàn)程都應(yīng)該有它自己的 SqlSession 實(shí)例。SqlSession 的實(shí)例不是線(xiàn)程安全的,因此是不能被共享的,所以它的最佳的作用域是請(qǐng)求或方法作用域。

    • 用完之后需要趕緊關(guān)閉,否則資源被占用!

      @Test public void addUser(){SqlSession sqlSession = MyBatisUtil.getSqlSession();try {UserMapper mapper = sqlSession.getMapper(UserMapper.class);mapper.insertUser(new User(8,"GCD","123456"));sqlSession.commit();}finally {if (sqlSession!=null){sqlSession.close();}}}

    這里的每一個(gè)mapper,就代表一個(gè)具體的業(yè)務(wù)!

    5、解決屬性名和字段名不一致的問(wèn)題

    1、問(wèn)題

    新建一個(gè)項(xiàng)目,拷貝之前的,測(cè)試實(shí)體類(lèi)字段不一致的情況

    */ public class User {private int id;private String name;private String password;...... }

    解決方法:

    • 起別名

      <select id="getUserById" resultType="User">select id, name, pwd as `password`from mybatis.userwhere id = #{id}; </select>

    2、resultMap

    結(jié)果集映射

    id name pwd id name passwod <?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE mapperPUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd"> <mapper namespace="com.sue.dao.UserMapper"><insert id="insertUser" parameterType="User">insert into mybatis.user (id,name,pwd)values (#{id},#{name},#{pwd});</insert><resultMap id="userMap" type="User"><!-- column數(shù)據(jù)庫(kù)列名-字段 property實(shí)體類(lèi)中的屬性名 --><result column="id" property="id"/><result column="name" property="name"/><result column="pwd" property="password"/></resultMap><select id="getUserById" resultMap="userMap">select *from mybatis.userwhere id = #{id}</select></mapper>
    • resultMap 元素是 MyBatis 中最重要最強(qiáng)大的元素
    • ResultMap 的設(shè)計(jì)思想是,對(duì)簡(jiǎn)單的語(yǔ)句做到零配置,對(duì)于復(fù)雜一點(diǎn)的語(yǔ)句,只需要描述語(yǔ)句之間的關(guān)系就行了。
    • ResultMap 的優(yōu)秀之處——你完全可以不用顯式地配置它們。

    如果這個(gè)世界總是這么簡(jiǎn)單就好了。

    6、日志

    6.1、日志工廠(chǎng)

    如果一個(gè)數(shù)據(jù)庫(kù)操作 出現(xiàn)了異常,我們需要排錯(cuò),日志就是最好的助手

    曾經(jīng):sout、debug

    現(xiàn)在:日志工廠(chǎng)

    • SLF4J
    • LOG4J(deprecated since 3.5.9)
    • LOG4J2
    • JDK_LOGGING
    • COMMONS_LOGGING
    • STDOUT_LOGGING
    • NO_LOGGING

    在mybatis中具體使用哪一個(gè)日志實(shí)現(xiàn),在設(shè)置中設(shè)定!

    STDOUT_LOGGING標(biāo)準(zhǔn)日志輸出

    在mybatis核心配置文件中添加日志配置

    <settings><!--標(biāo)準(zhǔn)的日志工廠(chǎng)實(shí)現(xiàn)--><setting name="logImpl" value="STDOUT_LOGGING"/> </settings>

    6.2、Log4J

    什么是Log4J

    • Log4j是Apache的一個(gè)開(kāi)源項(xiàng)目,通過(guò)使用Log4j,我們可以控制日志信息輸送的目的地是控制臺(tái)、文件、GUI組件;
    • 我們也可以控制每一條日志的輸出格式;
    • 通過(guò)定義每一條日志信息的級(jí)別,我們能夠更加細(xì)致地控制日志的生成過(guò)程;
    • 通過(guò)一個(gè)配置文件來(lái)靈活地進(jìn)行配置,而不需要修改應(yīng)用的代碼。
  • 導(dǎo)入log4j的包

    <!-- https://mvnrepository.com/artifact/log4j/log4j --> <dependency><groupId>log4j</groupId><artifactId>log4j</artifactId><version>1.2.17</version> </dependency>
  • log4j.properties

    #將等級(jí)為DEBUG的日志輸出到console和file這兩個(gè)目的地,console和file的定義在下面配置中 log4j.rootLogger=DEBUG, console, file#控制臺(tái)輸出的相關(guān)配置 log4j.appender.console=org.apache.log4j.ConsoleAppender log4j.appender.console.Target = System.out log4j.appender.console.Threshold=DEBUG log4j.appender.console.layout=org.apache.log4j.PatternLayout log4j.appender.console.layout.ConversionPattern=%d %p [%c] - %m%n#文件輸出的相關(guān)配置 log4j.appender.file=org.apache.log4j.RollingFileAppender log4j.appender.file.File=./log/zyy.log log4j.appender.file.MaxFileSize=10MB log4j.appender.file.Threshold=DEBUG log4j.appender.file.layout=org.apache.log4j.PatternLayout log4j.appender.file.layout.ConversionPattern=%d %p [%c] - %m%n#日志輸出級(jí)別 log4j.logger.org.mybatis=DEBUG log4j.logger.java.sql=DEBUG log4j.logger.java.sql.Statement=DEBUG log4j.logger.java.sql.ResultSet=DEBUG log4j.logger.java.sql.PreparedStatement=DEBUG
  • 配置log4j為mybatis日志的實(shí)現(xiàn)

    <settings><setting name="logImpl" value="LOG4J"/> </settings>
  • 使用log4j,運(yùn)行測(cè)試

  • 簡(jiǎn)單使用

  • 在要使用log4j的類(lèi)中,導(dǎo)入包import org.apache.log4j.Logger;

  • 日志對(duì)象,參數(shù)為當(dāng)前類(lèi)的class

    static Logger logger = Logger.getLogger(UserDaoTest.class);
  • 日志級(jí)別

    @Test public void testLog4j(){logger.info("info:進(jìn)入了testLog4j");logger.debug("debug:進(jìn)入了testLog4j");logger.error("error:進(jìn)入了testLog4j"); }
  • 7、分頁(yè)

    • 減少數(shù)據(jù)的處理量

    7.1、使用limit分頁(yè)

    -- 語(yǔ)法 select * from `user` limit startIndex,pageSize; select * from `user` limit 2; -- 相當(dāng)于 select * from `user` limit 0,2;

    使用mybatis實(shí)現(xiàn)分頁(yè),核心sql

  • 接口

    /** * 分頁(yè)查詢(xún) * @param map * @return */ List<User> getUserByLimit(Map<String, Integer> map);
  • Mapper.xml

    <select id="getUserByLimit" parameterType="map" resultMap="userMap">select id, name, pwd from `user` limit #{startIndex},#{pageSize} </select>
  • 測(cè)試

    @Test public void getUserByLimit() {SqlSession sqlSession = null;try {sqlSession = MybatisUtils.getSqlSession();UserMapper mapper = sqlSession.getMapper(UserMapper.class);Map<String, Integer> map = new HashMap<>(16);map.put("startIndex", 0);map.put("pageSize", 2);List<User> userList = mapper.getUserByLimit(map);for (User user : userList) {logger.info(user);}} finally {if (sqlSession != null) {sqlSession.close();}}}
  • 7.2、RowBounds分頁(yè)

    不再使用sql實(shí)現(xiàn)分頁(yè)

  • 接口

    /*** 分頁(yè)查詢(xún)* @return*/ List<User> getUserByRowBounds();
  • Mapper.xml

    <select id="getUserByRowBounds" resultMap="userMap">select id, name, pwd from `user` </select>
  • 測(cè)試

    @Test public void getUserByRowBounds() {SqlSession sqlSession = null;try {sqlSession = MybatisUtils.getSqlSession();RowBounds rowBounds = new RowBounds(1,2);List<User> userList = sqlSession.selectList("com.sue.dao.UserMapper.getUserByRowBounds",null, rowBounds);for (User user : userList) {logger.info(user);}} finally {if (sqlSession != null) {sqlSession.close();}}}
  • 7.3、分頁(yè)插件

    官方文檔:https://pagehelper.github.io/

    8、使用注解開(kāi)發(fā)

    8.1、面向接口編程

    • 根本原因:解耦,可拓展,提高復(fù)用,分層開(kāi)發(fā)中,上層不用管具體的實(shí)現(xiàn),大家都遵守共同的標(biāo)準(zhǔn),使得開(kāi)發(fā)變得容易,規(guī)范性更好。
    • 在一個(gè)面向?qū)ο蟮南到y(tǒng)中,系統(tǒng)的各種功能是由許許多多的不同對(duì)象協(xié)作完成的。在這種情況下,各個(gè)對(duì)象內(nèi)部是如何實(shí)現(xiàn)自己的,對(duì)系統(tǒng)設(shè)計(jì)人員來(lái)講就不用那么重要了;
    • 而各個(gè)對(duì)象之前的協(xié)作關(guān)系則成為系統(tǒng)設(shè)計(jì)的關(guān)鍵。小到不同類(lèi)之前的通訊,大到各模塊之間的交互,在系統(tǒng)設(shè)計(jì)之初都是要著重要考慮的,這也是系統(tǒng)設(shè)計(jì)的主要工作內(nèi)容。面向接口編程就是指按照這種思想來(lái)編程。

    關(guān)于接口的理解

    • 接口從更深層次的理解,應(yīng)是定義(規(guī)范,約束)與實(shí)現(xiàn)(名實(shí)分離的原則)的分離
    • 接口的本身反映了系統(tǒng)設(shè)計(jì)人員對(duì)系統(tǒng)的抽象理解
    • 接口應(yīng)有兩類(lèi):
      • 第一類(lèi)是對(duì)一個(gè)個(gè)體的抽象,它對(duì)應(yīng)為一個(gè)抽象體(abstract class)
      • 第二類(lèi)是對(duì)一個(gè)個(gè)體某一方便的抽象,即形成一個(gè)抽象面(interface)
    • 一個(gè)個(gè)體有可能有多個(gè)抽象面。抽象體和抽象面是有區(qū)別的。

    三個(gè)面向區(qū)別

    • 面向?qū)ο?#xff0c;我們考慮問(wèn)題時(shí),以對(duì)象為單位,考慮它的屬性及方法
    • 面向過(guò)程,我們考慮問(wèn)題時(shí),以一個(gè)具體的流程(事務(wù)過(guò)程)為單位,考慮它的實(shí)現(xiàn)
    • 接口設(shè)計(jì)與非接口設(shè)計(jì)是針對(duì)復(fù)用技術(shù)而言的,與面向?qū)ο?#xff08;過(guò)程)不是一個(gè)問(wèn)題。更多的體現(xiàn)就是對(duì)系統(tǒng)整體的架構(gòu)。

    8.2、使用注解開(kāi)發(fā)

  • 注解在接口上實(shí)現(xiàn)

    public interface UserMapper {@Select("select * from user")List<User> getUserList(); }
  • 需要在核心配置文件中綁定接口

    <mappers><mapper class="com.sue.dao.UserMapper"/> </mappers>
  • 測(cè)試

    package com.sue.dao;import com.sue.pojo.User; import com.sue.utils.MyBatisUtil; import org.apache.ibatis.session.SqlSession; import org.junit.Test;import java.util.HashMap; import java.util.List;public class UserMapperTest {@Testpublic void test(){SqlSession sqlSession = MyBatisUtil.getSqlSession();//底層主要用反射try {UserMapper mapper = sqlSession.getMapper(UserMapper.class);List<User> userList = mapper.getUserList();for (User user : userList) {System.out.println(user);}}finally {if (sqlSession!=null){sqlSession.close();}}} }
  • 本質(zhì):反射機(jī)制實(shí)現(xiàn)

    底層:動(dòng)態(tài)代理

    mybatis詳細(xì)的執(zhí)行流程

    8.3、CRUD

    我們可以造工具類(lèi)創(chuàng)建的時(shí)候?qū)崿F(xiàn)自動(dòng)提交事務(wù)!

    public static SqlSession getSqlSession() {return sqlSessionFactory.openSession(true); }

    編寫(xiě)接口,增加注解

    import com.sue.pojo.User; import org.apache.ibatis.annotations.Delete; import org.apache.ibatis.annotations.Insert; import org.apache.ibatis.annotations.Param; import org.apache.ibatis.annotations.Select; import org.apache.ibatis.annotations.Update;import java.util.List;/*** @Description: 接口描述* @Author: com.zyy* @Date: 2022/03/12 09:41*/ public interface UserMapper {@Select("select id, name, pwd from `user`")List<User> getUserList();@Select("select id, name, pwd from `user` where id=#{id} ")User getUserById(@Param("id") int id);@Insert("insert into `user`(id, name, pwd) values (#{id},#{name},#{password})")int addUser(User user);@Update("update `user` set name=#{name},pwd=#{password} where id=#{id}")int updateUser(User user);@Delete("delete from `user` where id=#{uid}")int deleteUser(@Param("uid") int id); }

    【注意:我們必須要將接口注冊(cè)綁定到我們的核心配置文件中】

    關(guān)于@Param()注解

    • 基本類(lèi)型的參數(shù)或者String類(lèi)型,需要加上
    • 引用類(lèi)型不需要加
    • 如果只有一個(gè)基本類(lèi)型的話(huà),可以忽略,但是建議大家都加上
    • 我們?cè)趕ql中引用的就是我們這里的@Param()中設(shè)定的屬性名

    #{} ${}區(qū)別

    參考博客

    9、Lombok

    使用步驟

  • 在idea中安裝lombok插件

  • 在項(xiàng)目中導(dǎo)入lombok的jar包

    <!-- https://mvnrepository.com/artifact/org.projectlombok/lombok --> <dependency><groupId>org.projectlombok</groupId><artifactId>lombok</artifactId><version>1.18.24</version> </dependency>
  • 在實(shí)體類(lèi)上加注解即可

    package com.sue.pojo;import lombok.Data;/*** Created with IntelliJ IDEA.** @author : Genius Sue* @version : 1.0* @Project : Mybatis-Study* @Package : com.sue.pojo* @ClassName : .java* @createTime : 2022/9/8 9:24* @Email : 1420779618@qq.com* @公眾號(hào) :* @Website :* @Description :*/ @Data @AllArgsConstructor @NoArgsConstructor public class User {private int id;private String name;private String password;}
  • 注解

    @Getter and @Setter @FieldNameConstants @ToString @EqualsAndHashCode @AllArgsConstructor, @RequiredArgsConstructor and @NoArgsConstructor @Log, @Log4j, @Log4j2, @Slf4j, @XSlf4j, @CommonsLog, @JBossLog, @Flogger, @CustomLog @Data @Builder @SuperBuilder @Singular @Delegate @Value @Accessors @Wither @With @SneakyThrows @val @var

    實(shí)現(xiàn)原理:

    99%的程序員都在用Lombok,原理竟然這么簡(jiǎn)單?我也手?jǐn)]了一個(gè)!|建議收藏!!! - 云+社區(qū) - 騰訊云 (tencent.com)

    10、多對(duì)一處理

    多對(duì)一:

    • 多個(gè)學(xué)生,對(duì)應(yīng)一個(gè)老師
    • 對(duì)于學(xué)生而言, 關(guān)聯(lián) ,多個(gè)學(xué)生,關(guān)聯(lián)一個(gè)老師【多對(duì)一】
    • 對(duì)于老師而言, 集合 ,一個(gè)老師有很多學(xué)生【一對(duì)多】

    SQL

    CREATE TABLE `teacher` (`id` INT(10) NOT NULL,`name` VARCHAR(30) DEFAULT NULL,PRIMARY KEY (`id`) ) ENGINE = INNODBDEFAULT CHARSET = utf8;INSERT INTO teacher(`id`, `name`) VALUES (1, '秦老師');CREATE TABLE `student` (`id` INT(10) NOT NULL,`name` VARCHAR(30) DEFAULT NULL,`tid` INT(10) DEFAULT NULL,PRIMARY KEY (`id`),KEY `fktid` (`tid`),CONSTRAINT `fktid` FOREIGN KEY (`tid`) REFERENCES `teacher` (`id`) ) ENGINE = INNODBDEFAULT CHARSET = utf8;INSERT INTO `student` (`id`, `name`, `tid`) VALUES ('1', '小明', '1'); INSERT INTO `student` (`id`, `name`, `tid`) VALUES ('2', '小紅', '1'); INSERT INTO `student` (`id`, `name`, `tid`) VALUES ('3', '小張', '1'); INSERT INTO `student` (`id`, `name`, `tid`) VALUES ('4', '小李', '1'); INSERT INTO `student` (`id`, `name`, `tid`) VALUES ('5', '小王', '1');

    測(cè)試環(huán)境搭建

  • 導(dǎo)入lombok
  • 新建實(shí)體類(lèi)Teacher,Student
  • 建立Mapper接口
  • 建立Mapper.xml文件
  • 在核心配置文件中綁定注冊(cè)我們的Mapper接口或者文件【方式很多,自選】
  • 測(cè)試查詢(xún)是否能夠成功!
  • Student.java

    @Data public class Student {private int id;private String name;private Teacher teacher; }

    Teacher.java

    @Data public class Teacher {private int id;private String name; }

    按照查詢(xún)嵌套處理

    <?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE mapperPUBLIC "-//mybatis.org//DTD mapper 3.0//EN""http://mybatis.org/dtd/mybatis-3-mapper.dtd"><mapper namespace="com.sue.dao.StudentMapper"><!--思路:1. 查詢(xún)所有的學(xué)生信息2. 根據(jù)查詢(xún)出來(lái)的學(xué)生的tid,尋找對(duì)應(yīng)的老師 子查詢(xún)--><select id="getStudent" resultMap="studentTeacher">select *from student;</select><resultMap id="studentTeacher" type="Student"><!-- 復(fù)雜的屬性,我們需要單獨(dú)處理 對(duì)象:association 集合:collection --><association property="teacher" column="tid" javaType="Teacher" select="getTeacher"/></resultMap><select id="getTeacher" resultType="Teacher">select *from teacherwhere id=#{id};</select></mapper>

    按照結(jié)果嵌套處理

    <!-- 按照結(jié)果嵌套處理 --><select id="getStudent2" resultMap="studentTeacher2">select s.id sid,s.name sname,t.name tname,t.idfrom student s,teacher twhere s.tid=t.id; </select><resultMap id="studentTeacher2" type="Student"><result property="id" column="sid"/><result property="name" column="sname"/><association property="teacher" javaType="Teacher"><result property="name" column="tname"/><result property="id" column="id"/></association> </resultMap>

    回顧mysql多對(duì)一查詢(xún)方式:

    • 子查詢(xún)
    • 鏈表查詢(xún)

    11、一對(duì)多處理

    比如:一個(gè)老師擁有多個(gè)學(xué)生!

    對(duì)于老師而言,就是一對(duì)多的關(guān)系!

    環(huán)境搭建

    實(shí)體類(lèi)

    @Data public class Student {private int id;private String name;//關(guān)聯(lián)一個(gè)老師private int tid;} @Data public class Teacher {private int id;private String name;//一個(gè)老師有多個(gè)學(xué)生private List<Student> students; }

    按照結(jié)果嵌套處理

    <?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE mapperPUBLIC "-//mybatis.org//DTD mapper 3.0//EN""http://mybatis.org/dtd/mybatis-3-mapper.dtd"><mapper namespace="com.sue.dao.TeacherMapper"><!-- 按結(jié)果嵌套查詢(xún) --><select id="getTeacher" resultMap="TeacherStudent">select s.id sid,s.name sname,t.name tname,t.id tidfrom teacher t ,student swhere s.tid=t.id and t.id=#{tid}</select><resultMap id="TeacherStudent" type="Teacher"><result property="id" column="tid"/><result property="name" column="tname"/><!--復(fù)雜的屬性,我們需要單獨(dú)處理 集合:collectionjavaType="" 執(zhí)行屬性的類(lèi)型集合中的泛型信息,我們使用ofType獲取--><collection property="students" ofType="Student"><result property="id" column="sid"/><result property="name" column="sname"/><result property="tid" column="tid"/></collection></resultMap></mapper>

    按照查詢(xún)嵌套處理

    <select id="getTeacher2" resultMap="TeacherStudent2">select * from teacher where id = #{tid} </select> <resultMap id="TeacherStudent2" type="Teacher"><collection property="students" javaType="ArrayList" ofType="Student" select="getStudentByTeacherId" column="id"/> </resultMap> <select id="getStudentByTeacherId" resultType="Student">select * from student where tid=#{tid} </select>

    小結(jié)

  • 關(guān)聯(lián) - association【多對(duì)一】
  • 集合 - collection【一對(duì)多】
  • javaType & ofType
    • javaType 用來(lái)指定實(shí)體類(lèi)中屬性的類(lèi)型
    • ofType 用來(lái)指定映射到List或者集合中pojo類(lèi)型,泛型中的約束類(lèi)型。
  • 注意點(diǎn)

    • 保證sql的可讀性,盡量保證通俗易懂
    • 注意一對(duì)多和多對(duì)一中,屬性和字段的問(wèn)題
    • 如果問(wèn)題不好排查錯(cuò)誤,可以使用日志,建議使用Log4j

    面試高頻:

    • mysql引擎
    • innoDB底層原理
    • 索引
    • 索引優(yōu)化

    12、動(dòng)態(tài)SQL

    什么是動(dòng)態(tài)sql:動(dòng)態(tài)sql就是根據(jù)不同的條件生成不同的sql語(yǔ)句。

    如果你之前用過(guò) JSTL 或任何基于類(lèi) XML 語(yǔ)言的文本處理器,你對(duì)動(dòng)態(tài) SQL 元素可能會(huì)感覺(jué)似曾相識(shí)。在 MyBatis 之前的版本中,需要花時(shí)間了解大量的元素。借助功能強(qiáng)大的基于 OGNL 的表達(dá)式,MyBatis 3 替換了之前的大部分元素,大大精簡(jiǎn)了元素種類(lèi),現(xiàn)在要學(xué)習(xí)的元素種類(lèi)比原來(lái)的一半還要少。

    • if
    • choose (when, otherwise)
    • trim (where, set)
    • foreach

    搭建環(huán)境

    CREATE TABLE `blog` (`id` VARCHAR(50) NOT NULL COMMENT '博客id',`title` VARCHAR(100) NOT NULL COMMENT '博客標(biāo)題',`author` VARCHAR(30) NOT NULL COMMENT '博客作者',`create_time` DATETIME NOT NULL COMMENT '創(chuàng)建時(shí)間',`views` INT(30) NOT NULL COMMENT '瀏覽量' ) ENGINE = INNODBDEFAULT CHARSET = utf8;

    創(chuàng)建一個(gè)基礎(chǔ)工程

  • 導(dǎo)包

  • 編寫(xiě)配置文件

  • 編寫(xiě)實(shí)體類(lèi)

    package com.sue.pojo;import lombok.AllArgsConstructor; import lombok.Data; import lombok.NoArgsConstructor;import java.util.Date;@Data @AllArgsConstructor @NoArgsConstructor public class Blog {private String id;private String title;private String author;private Date createTime;//屬性名和字段名不一致private int views;}
  • 編寫(xiě)實(shí)體類(lèi)對(duì)應(yīng)Mapper接口和Mapper.xml文件

  • if

    <?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE mapperPUBLIC "-//mybatis.org//DTD Config 3.0//EN""http://mybatis.org/dtd/mybatis-3-mapper.dtd"><mapper namespace="com.sue.dao.BlogMapper"><insert id="addBlog" parameterType="Blog">insert into mybatis.blog(id, title, author, create_time, views)values (#{id},#{title},#{author},#{createTime},#{views});</insert><select id="queryBlogIF" parameterType="Map" resultType="Blog">select *from mybatis.blogwhere 1=1<if test="title!=null">and title=#{title}</if><if test="author!=null">and author=#{author}</if></select></mapper>

    choose (when, otherwise)

    <select id="queryBlogChoose" parameterType="Map" resultType="Blog">select *from mybatis.blog<where><choose><when test="title!=null">title=#{title}</when><when test="author!=null">and author=#{author}</when><otherwise>and views=#{views}</otherwise></choose></where> </select>

    trim (where, set)

    where 元素只會(huì)在子元素返回任何內(nèi)容的情況下才插入 “WHERE” 子句。而且,若子句的開(kāi)頭為 “AND” 或 “OR”,where 元素也會(huì)將它們?nèi)コ?/p> <select id="queryBlogIF" parameterType="Map" resultType="Blog">select *from mybatis.blog<where><if test="title!=null">and title=#{title}</if><if test="author!=null">and author=#{author}</if></where></select> <update id="updateBlog" parameterType="Map">update mybatis.blog<set><if test="title!=null">title=#{title},</if><if test="author!=null">author=#{author},</if></set>where id=#{id}; </update>

    如果 where 元素與你期望的不太一樣,你也可以通過(guò)自定義 trim 元素來(lái)定制 where 元素的功能。比如,和 where 元素等價(jià)的自定義 trim 元素為:

    <trim prefix="WHERE" prefixOverrides="AND |OR ">... </trim> <trim prefix="SET" suffixOverrides=",">... </trim>

    所謂的動(dòng)態(tài)sql。本質(zhì)還是sql語(yǔ)句,只是我們可以在sql層面,去執(zhí)行一個(gè)邏輯代碼

    SQL片段

    有的時(shí)候,我們可能會(huì)將一些功能的部分抽取出來(lái),方便復(fù)用

  • 使用sql標(biāo)簽抽取公共的部分

    <sql id="title-author-views"><choose><when test="title != null">title like #{title}</when><when test="author != null">and author = #{author}</when><otherwise>and views=#{views}</otherwise></choose> </sql>
  • 在需要使用的地方使用include標(biāo)簽引用即可

    <select id="getBlogList" parameterType="map" resultType="com.sue.pojo.Blog">select id,title,author,create_time createTime,views from blog<where><include refid="title-author-views"/></where> </select>
  • 注意事項(xiàng):

    • 最好基于單表來(lái)定義sql片段
    • 不要存在where標(biāo)簽

    foreach

    <!--select id,title,author,create_time createTime,views from blog where 1=1 and (id ='1' or id='2'or id='3')--> <select id="getBlogListForeach" parameterType="map" resultType="com.sue.pojo.Blog">select id,title,author,create_time createTime,views from blog<where><foreach collection="idList" item="id" open="(" close=")" separator="or">id = #{id}</foreach></where> </select>

    動(dòng)態(tài)sql就是在拼接sql語(yǔ)句,我們只要保證sql正確性,按照sql的格式,去排列組合就可以了

    <select id="queryBlogForeach" parameterType="Map" resultType="Blog">select *from mybatis.blog<where><foreach collection="ids" item="id" open="and (" separator="or" close=")">id=#{id}</foreach></where> </select> SqlSession sqlSession = MyBatisUtil.getSqlSession(); try {BlogMapper mapper = sqlSession.getMapper(BlogMapper.class);HashMap map = new HashMap();ArrayList<Integer> ids=new ArrayList<Integer>();ids.add(1);ids.add(2);map.put("ids", ids);List<Blog> blogs = mapper.queryBlogForeach(map);for (Blog blog : blogs) {System.out.println(blog);} } finally {if (sqlSession!=null){sqlSession.close();} }

    13、緩存

    13.1、簡(jiǎn)介

  • 什么是緩存[cache]
    • 存在內(nèi)存中的臨時(shí)數(shù)據(jù)
    • 將用戶(hù)經(jīng)常查詢(xún)的數(shù)據(jù)放在緩存(內(nèi)存)中,用戶(hù)去查詢(xún)數(shù)據(jù)就不用從磁盤(pán)上(關(guān)系型數(shù)據(jù)庫(kù)數(shù)據(jù)文件)查詢(xún),從緩存中查詢(xún),從而提高查詢(xún)效率,解決了高并發(fā)系統(tǒng)的性能問(wèn)題。
  • 為什么使用緩存
    • 減少和數(shù)據(jù)庫(kù)的交互次數(shù),減少系統(tǒng)開(kāi)銷(xiāo),提高系統(tǒng)效率
  • 什么樣的數(shù)據(jù)能使用緩存
    • 經(jīng)常查詢(xún)并且不經(jīng)常改變的數(shù)據(jù)
  • 13.2、mybatis緩存

    • mybatis包含一個(gè)非常強(qiáng)大的查詢(xún)緩存特性,它可以非常方便地定制和配置緩存。緩存可以極大的提高查詢(xún)效率。
    • mybatis系統(tǒng)中默認(rèn)定義了兩級(jí)緩存:一級(jí)緩存二級(jí)緩存
      • 默認(rèn)情況下,只有一級(jí)緩存開(kāi)啟。(sqlsession級(jí)別的緩存,也稱(chēng)為本地緩存)
      • 二級(jí)緩存需要手動(dòng)開(kāi)啟和配置,它是基于namespace級(jí)別的緩存。
      • 為了提高擴(kuò)展性,mybatis定義了緩存接口cache。我們可以通過(guò)實(shí)現(xiàn)cache接口來(lái)自定義二級(jí)緩存。

    13.3、一級(jí)緩存

    • 一級(jí)緩存也叫本次緩存
      • 與數(shù)據(jù)庫(kù)同一次會(huì)話(huà)期間查詢(xún)到的數(shù)據(jù)會(huì)放到本次緩存中。
      • 以后如果需要獲取相同的數(shù)據(jù),直接從緩存中拿,沒(méi)必須再去查詢(xún)數(shù)據(jù)庫(kù)
  • 開(kāi)啟日志

  • 測(cè)試再一個(gè)session中查詢(xún)兩次相同的記錄

    package com.sue.dao;import com.sue.pojo.User; import com.sue.utils.MyBatisUtil; import org.apache.ibatis.session.SqlSession; import org.junit.Test;import java.util.List;public class MyTest {@Testpublic void getUserById() {SqlSession sqlSession = MyBatisUtil.getSqlSession();try {UserMapper mapper = sqlSession.getMapper(UserMapper.class);User user1 = mapper.queryUserById(1);System.out.println(user1);System.out.println("==================");User user2 = mapper.queryUserById(1);System.out.println(user2);System.out.println(user1 == user2);} finally {if (sqlSession != null) {sqlSession.close();}}} }
  • 查詢(xún)?nèi)罩据敵?/p>

  • 緩存失效的情況:

  • 查詢(xún)條件不同
  • 增刪改操作,可能會(huì)改變?cè)瓉?lái)的數(shù)據(jù),所以必定會(huì)刷新緩存
  • 查詢(xún)不同的Mapper.xml

  • 手動(dòng)清理緩存

    package com.sue.dao;import com.sue.pojo.User; import com.sue.utils.MyBatisUtil; import org.apache.ibatis.session.SqlSession; import org.junit.Test;import java.util.List;public class MyTest {@Testpublic void getUserById() {SqlSession sqlSession = MyBatisUtil.getSqlSession();try {UserMapper mapper = sqlSession.getMapper(UserMapper.class);User user1 = mapper.queryUserById(1);System.out.println(user1);System.out.println("==================");//手動(dòng)清理緩存sqlSession.clearCache();User user2 = mapper.queryUserById(2);System.out.println(user2);System.out.println(user1 == user2);} finally {if (sqlSession != null) {sqlSession.close();}}} }
  • 小結(jié):

    • 一級(jí)緩存默認(rèn)是開(kāi)啟的,只在一次sqlsession中有效,也就是拿到連接到關(guān)閉了連接這個(gè)區(qū)間段!
    • 一級(jí)緩存就是一個(gè)map

    13.4、二級(jí)緩存

    • 二級(jí)緩存也叫全局緩存,一級(jí)緩存作用域太低了,所以誕生了二級(jí)緩存。
    • 基本namespace級(jí)別的緩存,一個(gè)名稱(chēng)空間,對(duì)應(yīng)一個(gè)二級(jí)緩存
    • 工作機(jī)制
      • 一個(gè)會(huì)話(huà)查詢(xún)一個(gè)數(shù)據(jù),這個(gè)數(shù)據(jù)就會(huì)被放到當(dāng)前會(huì)話(huà)的一級(jí)緩存中
      • 如果當(dāng)前會(huì)話(huà)關(guān)閉了,這個(gè)會(huì)話(huà)對(duì)應(yīng)的一級(jí)緩存就沒(méi)了,但是我們想要的是,會(huì)話(huà)關(guān)閉了,一級(jí)緩存中的數(shù)據(jù)被保存到二級(jí)緩存中
      • 新的會(huì)話(huà)查詢(xún)信息,就可以直接從二級(jí)緩存中獲取內(nèi)容
      • 不同的mapper查出的數(shù)據(jù)會(huì)放在自己對(duì)應(yīng)的緩存(map)中

    步驟

  • 開(kāi)啟全部緩存

    mybatis-config.xml

    <settings><setting name="logImpl" value="STDOUT_LOGGING"/><!-- 顯式開(kāi)啟全局緩存--><setting name="cacheEnabled" value="true"/> </settings>
  • 在要使用二級(jí)緩存的mapper中開(kāi)啟

    <!-- 在當(dāng)前mapper.xml中使用二級(jí)緩存--> <cache/>

    也可以自定義參數(shù)

    <!-- 在當(dāng)前mapper.xml中使用二級(jí)緩存--> <cacheeviction="FIFO"flushInterval="60000"size="512"readOnly="true"/>
  • 測(cè)試

    @Test public void getUserById2() {SqlSession sqlSession = MybatisUtils.getSqlSession();UserMapper mapper = sqlSession.getMapper(UserMapper.class);User user1 = mapper.getUserById(1);System.out.println(user1);sqlSession.close();System.out.println("==================");SqlSession sqlSession2 = MybatisUtils.getSqlSession();UserMapper mapper2 = sqlSession2.getMapper(UserMapper.class);User user2 = mapper2.getUserById(1);System.out.println(user2);System.out.println(user1 == user2);sqlSession2.close(); }

  • 問(wèn)題:我們需要將實(shí)體類(lèi)序列化,否則就會(huì)報(bào)錯(cuò)

    Caused by: java.io.NotSerializableException: com.sue.pojo.User

    解決

    public class User implements Serializable { }
  • 小結(jié):

    • 只要開(kāi)啟了二級(jí)緩存,在同一個(gè)Mapper下就有效
    • 所有的數(shù)據(jù)都會(huì)先放在一級(jí)緩存中
    • 只有當(dāng)會(huì)話(huà)提交或者關(guān)閉的時(shí)候,才會(huì)提交到二級(jí)緩存中

    13.5、緩存原理

  • 先查詢(xún)的二級(jí)緩存,查到直接返回
  • 查不到,再查一級(jí)緩存,查到直接返回
  • 查不到,查數(shù)據(jù)庫(kù)
  • @Test public void getUserById2() {SqlSession sqlSession = MybatisUtils.getSqlSession();UserMapper mapper = sqlSession.getMapper(UserMapper.class);//查表User user1 = mapper.getUserById(1);System.out.println(user1);//查的一級(jí)緩存User user11 = mapper.getUserById(1);System.out.println(user11);System.out.println(user1 == user11);sqlSession.close();System.out.println("==================");SqlSession sqlSession2 = MybatisUtils.getSqlSession();UserMapper mapper2 = sqlSession2.getMapper(UserMapper.class);//查表User user2 = mapper2.getUserById(2);System.out.println(user2);sqlSession2.close();System.out.println("==================");SqlSession sqlSession3 = MybatisUtils.getSqlSession();UserMapper mapper3 = sqlSession3.getMapper(UserMapper.class);//查二級(jí)緩存User user3 = mapper3.getUserById(2);System.out.println(user3);System.out.println(user2 == user3);sqlSession3.close(); }

    結(jié)果如下

    PooledDataSource forcefully closed/removed all connections. PooledDataSource forcefully closed/removed all connections. PooledDataSource forcefully closed/removed all connections. PooledDataSource forcefully closed/removed all connections. Cache Hit Ratio [com.sue.dao.UserMapper]: 0.0 Opening JDBC Connection Created connection 867398280. ==> Preparing: select id,name,pwd from user where id=? ==> Parameters: 1(Integer) <== Columns: id, name, pwd <== Row: 1, sue, 123456 <== Total: 1 User(id=1, name=zyy, pwd=123456) Cache Hit Ratio [com.sue.dao.UserMapper]: 0.0 User(id=1, name=sue, pwd=123456) true Closing JDBC Connection [com.mysql.jdbc.JDBC4Connection@33b37288] Returned connection 867398280 to pool. ================== Cache Hit Ratio [com.sue.dao.UserMapper]: 0.0 Opening JDBC Connection Checked out connection 867398280 from pool. ==> Preparing: select id,name,pwd from user where id=? ==> Parameters: 2(Integer) <== Columns: id, name, pwd <== Row: 2, 張三, 111111 <== Total: 1 User(id=2, name=張三, pwd=111111) Closing JDBC Connection [com.mysql.jdbc.JDBC4Connection@33b37288] Returned connection 867398280 to pool. ================== As you are using functionality that deserializes object streams, it is recommended to define the JEP-290 serial filter. Please refer to https://docs.oracle.com/pls/topic/lookup?ctx=javase15&id=GUID-8296D8E8-2B93-4B9A-856E-0A65AF9B8C66 Cache Hit Ratio [com.sue.dao.UserMapper]: 0.25 User(id=2, name=張三, pwd=111111) false

    13.6、自定義緩存-ehcache

    Ehcache是一種廣泛使用的開(kāi)源java分布式緩存,只要面向通用緩存。

    要在程序中使用ehcache,先導(dǎo)包

    <dependency><groupId>org.mybatis.caches</groupId><artifactId>mybatis-ehcache</artifactId><version>1.1.0</version> </dependency>

    在mapper中指定使用我們的ehcache緩存實(shí)現(xiàn)

    <cache type="org.mybatis.caches.ehcache.EhcacheCache"/>

    配置文件ehcache.xml

    <?xml version="1.0" encoding="UTF-8"?> <ehcache xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xsi:noNamespaceSchemaLocation="http://ehcache.org/ehcache.xsd"updateCheck="false"><!--diskStore:為緩存路徑,ehcache分為內(nèi)存和磁盤(pán)兩級(jí),此屬性定義磁盤(pán)的緩存位置。參數(shù)解釋如下:user.home – 用戶(hù)主目錄user.dir – 用戶(hù)當(dāng)前工作目錄java.io.tmpdir – 默認(rèn)臨時(shí)文件路徑--><diskStore path="./tmpdir/Tmp_EhCache"/><defaultCacheeternal="false"maxElementsInMemory="10000"overflowToDisk="false"diskPersistent="false"timeToIdleSeconds="1800"timeToLiveSeconds="259200"memoryStoreEvictionPolicy="LRU"/><cachename="cloud_user"eternal="false"maxElementsInMemory="5000"overflowToDisk="false"diskPersistent="false"timeToIdleSeconds="1800"timeToLiveSeconds="1800"memoryStoreEvictionPolicy="LRU"/><!--defaultCache:默認(rèn)緩存策略,當(dāng)ehcache找不到定義的緩存時(shí),則使用這個(gè)緩存策略。只能定義一個(gè)。--><!--name:緩存名稱(chēng)。maxElementsInMemory:緩存最大數(shù)目maxElementsOnDisk:硬盤(pán)最大緩存?zhèn)€數(shù)。eternal:對(duì)象是否永久有效,一但設(shè)置了,timeout將不起作用。overflowToDisk:是否保存到磁盤(pán),當(dāng)系統(tǒng)當(dāng)機(jī)時(shí)timeToIdleSeconds:設(shè)置對(duì)象在失效前的允許閑置時(shí)間(單位:秒)。僅當(dāng)eternal=false對(duì)象不是永久有效時(shí)使用,可選屬性,默認(rèn)值是0,也就是可閑置時(shí)間無(wú)窮大。timeToLiveSeconds:設(shè)置對(duì)象在失效前允許存活時(shí)間(單位:秒)。最大時(shí)間介于創(chuàng)建時(shí)間和失效時(shí)間之間。僅當(dāng)eternal=false對(duì)象不是永久有效時(shí)使用,默認(rèn)是0.,也就是對(duì)象存活時(shí)間無(wú)窮大。diskPersistent:是否緩存虛擬機(jī)重啟期數(shù)據(jù) Whether the disk store persists between restarts of the Virtual Machine. The default value is false.diskSpoolBufferSizeMB:這個(gè)參數(shù)設(shè)置DiskStore(磁盤(pán)緩存)的緩存區(qū)大小。默認(rèn)是30MB。每個(gè)Cache都應(yīng)該有自己的一個(gè)緩沖區(qū)。diskExpiryThreadIntervalSeconds:磁盤(pán)失效線(xiàn)程運(yùn)行時(shí)間間隔,默認(rèn)是120秒。memoryStoreEvictionPolicy:當(dāng)達(dá)到maxElementsInMemory限制時(shí),Ehcache將會(huì)根據(jù)指定的策略去清理內(nèi)存。默認(rèn)策略是LRU(最近最少使用)。你可以設(shè)置為FIFO(先進(jìn)先出)或是LFU(較少使用)。clearOnFlush:內(nèi)存數(shù)量最大時(shí)是否清除。memoryStoreEvictionPolicy:可選策略有:LRU(最近最少使用,默認(rèn)策略)、FIFO(先進(jìn)先出)、LFU(最少訪(fǎng)問(wèn)次數(shù))。FIFO,first in first out,這個(gè)是大家最熟的,先進(jìn)先出。LFU, Less Frequently Used,就是上面例子中使用的策略,直白一點(diǎn)就是講一直以來(lái)最少被使用的。如上面所講,緩存的元素有一個(gè)hit屬性,hit值最小的將會(huì)被清出緩存。LRU,Least Recently Used,最近最少使用的,緩存的元素有一個(gè)時(shí)間戳,當(dāng)緩存容量滿(mǎn)了,而又需要騰出地方來(lái)緩存新的元素的時(shí)候,那么現(xiàn)有緩存元素中時(shí)間戳離當(dāng)前時(shí)間最遠(yuǎn)的元素將被清出緩存。--></ehcache>

    總結(jié)

    以上是生活随笔為你收集整理的【SSM框架】MyBatis的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。

    如果覺(jué)得生活随笔網(wǎng)站內(nèi)容還不錯(cuò),歡迎將生活随笔推薦給好友。