主頁 > 後端開發 > Mybatis

Mybatis

2023-03-28 07:40:20 後端開發

Mybatis

環境:jdk mysql maven idea

SSM框架、組態檔的,

一、簡介

1.1、什么是Mybatis?

Mysbatis是一款優秀的持久化框架

它支持制定化SQL,存盤過以及高級映射

Mybatis避免了幾乎所有的JDBC代碼和手動設定引數以及獲取結果集

Mybatis可以使用簡單的XML或注解來配置和映射原生型別,介面和POJO為資料庫中的記錄

Mybatis原本是apache的一個開源專案Batis2010年這個專案由apache software foundation遷移到了Google code,并改名為Mybati

2013年11月遷移到Github如何獲得mybatis?

Maven廠庫:

Maven下載網址:https://www.mybatis.org/mybatis-3Maven <!-- https://mvnrepository.com/artifact/org.mybatis/mybatis -->

 <dependency> 
?
?    <groupId>org.mybatis</groupId>
?
?     <artifactId>mybatis</artifactId>
?
?     <version>3.5.11</version>
?
 </dependency>

Github網址: https://github.com/mybatis/mybatis-3中午網:https://mybatis.net.cn/

1.2、持久化

資料持久化

持久化就是將程式的資料在持久狀態和瞬時狀態轉化的程序

記憶體斷電即失資料庫(jdbc)、io檔案持久化

為什么需要持久化?

有一些物件,不能丟記憶體太貴了

13、持久層

Dao層、Service層、Controller層

完成持久化作業的代碼塊

層界十分明顯

1.4、為什么需要Mybatis?

幫助程式員將資料存入資料庫中

方便

傳統的jdbc太復雜了、簡化、框架、自動化

不用mybatis也可以,更容易上手優點:

簡單易學

靈活

Sql和代碼的分離,提高了可維護性

提供映射標簽,支持物件與資料庫的orm欄位關系映射

提供物件關系標簽,支持物件關系組建維護

提供xml標簽,支持撰寫動態sql

*使用的人多

二、創建一個Mybatis專案

1、創建maven專案

2、匯入依賴包

<dependencies>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.47</version>
</dependency>
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.5.10</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.13.2</version>
</dependency>
</dependencies>

這里的mybatis就是mybatis的依賴

3、創建工具類

package com.zeng.mybatis.utils;
?
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;
?
public class MybatisUtils {
public static SqlSessionFactory sqlSessionFactory;
static {
try {
String resource = "mybatis-config.xml";
InputStream inputStream = Resources.getResourceAsStream(resource);
sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
} catch (IOException e) {
e.printStackTrace();
}
}
public static SqlSession getSqlSession(){
return sqlSessionFactory.openSession();
}
}

4、創建物體類

package com.zeng.mybatis.pojo;
?
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;
}
?
@Override
public String toString() {
return "User{" +
"id=" + id +
", name='" + name + '\'' +
", pwd='" + pwd + '\'' +
'}';
}
}

5、創建Mapper介面

package com.zeng.mybatis.dao;
?
import com.zeng.mybatis.pojo.User;
?
import java.util.List;
?
public interface UserDao {
List<User> getUserList();
User getUserId(int id);
int addUser(User user);
int updateUser(User user);
int deleteUser(int id);
}

6、創建Mapper介面對應的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.zeng.mybatis.dao.UserDao">
<select id="getUserList" resultType="com.zeng.mybatis.pojo.User">
select * from User
</select>
</mapper>

7、在resources包下創建連接資料庫的對應資訊.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>
<environments default="development">
<environment id="development">
<transactionManager type="JDBC"/>
<dataSource type="POOLED">
<property name="driver" value="com.mysql.jdbc.Driver"/>
<property name="url" value="jdbc:mysql://localhost:3306/mybatis?characterEncoding=utf-8&amp;serverTimezone=UTC&amp;useSSL=false"/>
<property name="username" value="root"/>
<property name="password" value="12345678"/>
</dataSource>
</environment>
</environments>
<mappers>
<mapper resource="com/zeng/mybatis/dao/UserMapper.xml"/>
</mappers>
</configuration>

三、CRUD

1、namespace

namespace中的包名要和Dao/mapper介面中的包名一致

2、select

選擇、查詢陳述句

id:就是對應的namespace中的方法名

resultType:Sql陳述句執行的回傳值!

parameterType:引數型別

2.1、對應例子

Mapper.xml對應標簽

<select id="getUserId" resultType="com.zeng.mybatis.pojo.User" parameterType="int">
select * from User where id = #{id}
</select>

@Text測驗方法

@Test
public void getUserIdTest(){
SqlSession sqlSession = MybatisUtils.getSqlSession();
UserDao mapper = sqlSession.getMapper(UserDao.class);
User user = mapper.getUserId(1);
System.out.println(user);
}

3、insert增加標簽

Mapper.xml對應標簽

<insert id="addUser" parameterType="com.zeng.mybatis.pojo.User">
insert into User (id,name,pwd)
values (#{id},#{name},#{pwd});
</insert>

@Text測驗方

@Test
public void addUserTest(){
SqlSession sqlSession = MybatisUtils.getSqlSession();
UserDao mapper = sqlSession.getMapper(UserDao.class);
int row = mapper.addUser(new User(4, "丁鈺", "85200"));
sqlSession.commit();
if (row>0){
System.out.println("插入成功");
}
sqlSession.close();
}

4、update修改標簽

Mapper.xml對應標簽

<update id="updateUser" parameterType="com.zeng.mybatis.pojo.User">
update User
set name = #{name},pwd = #{pwd}
where id = #{id};
</update>

@Text測驗方法

@Test
public void updateUserTest(){
SqlSession sqlSession = MybatisUtils.getSqlSession();
UserDao mapper = sqlSession.getMapper(UserDao.class);
int row = mapper.updateUser(new User(4, "丁鈺兒", "7894"));
sqlSession.commit();
if (row>0){
System.out.println("修改成功");
}
sqlSession.close();
}

5、delete洗掉標簽

Mapper.xml對應標簽

<delete id="deleteUser" parameterType="int">
delete
from User
where id = #{id};
</delete>

@Text測驗方法

@Test
public void deleteUserTest(){
SqlSession sqlSession = MybatisUtils.getSqlSession();
UserDao mapper = sqlSession.getMapper(UserDao.class);
int row = mapper.deleteUser(4);
sqlSession.commit();
if (row>0){
System.out.println("洗掉成功");
}
sqlSession.close();
}
一定要記住增刪改的時候一定要增加事務

四、配置設定

configuration(配置)

properties(屬性)(重點)

settings(設定)(重點)

typeAliases(型別別名)(重點)

typeHandlers(型別處理器)

objectFactory(物件工廠)

plugins(插件)environments(環境配置)

environment(環境變數)

transactionManager(事務管理器)

dataSource(資料源)

databaseIdProvider(資料庫廠商標識)

mappers(映射器)(重點)

1、properties:

這些屬性可以在外部進行配置,并可以進行動態替換,你既可以在典型的 Java 屬性檔案中配置這些屬性,也可以在 properties 元素的子元素中設定,

例如:

<properties resource="org/mybatis/example/config.properties">
<property name="username" value="https://www.cnblogs.com/littlenoob/archive/2023/03/27/dev_user"/>
<property name="password" value="https://www.cnblogs.com/littlenoob/archive/2023/03/27/F2Fa3!33TYyg"/>
</properties>

設定好的屬性可以在整個組態檔中用來替換需要動態配置的屬性值,比如:

<dataSource type="POOLED">
<property name="driver" value="https://www.cnblogs.com/littlenoob/archive/2023/03/27/${driver}"/>
<property name="url" value="https://www.cnblogs.com/littlenoob/archive/2023/03/27/${url}"/>
<property name="username" value="https://www.cnblogs.com/littlenoob/archive/2023/03/27/${username}"/>
<property name="password" value="https://www.cnblogs.com/littlenoob/archive/2023/03/27/${password}"/>
</dataSource>

2、setting

cacheEnabled:全域性地開啟或關閉所有映射器組態檔中已配置的任何快取,true | falsetrue
lazyLoadingEnabled:延遲加載的全域開關,當開啟時,所有關聯物件都會延遲加載, 特定關聯關系中可通過設定 fetchType 屬性來覆寫該項的開關狀態,
logImpl:指定 MyBatis 所用日志的具體實作,未指定時將自動查找,SLF4J | LOG4J | LOG4J2 | JDK_LOGGING | COMMONS_LOGGING | STDOUT_LOGGING | NO_LOGGING

3、typeAliases:

型別別名可為 Java 型別設定一個縮寫名字, 它僅用于 XML 配置,意在降低冗余的全限定類名書寫,例如:

<typeAliases>
<typeAlias alias="Author" type="domain.blog.Author"/>
<typeAlias alias="Blog" type="domain.blog.Blog"/>
<typeAlias alias="Comment" type="domain.blog.Comment"/>
<typeAlias alias="Post" type="domain.blog.Post"/>
<typeAlias alias="Section" type="domain.blog.Section"/>
<typeAlias alias="Tag" type="domain.blog.Tag"/>
</typeAliases>

當這樣配置時,Blog 可以用在任何使用 domain.blog.Blog 的地方,

也可以指定一個包名,MyBatis 會在包名下面搜索需要的 Java Bean,比如:

<typeAliases>
<package name="domain.blog"/>
</typeAliases>每一個在包 domain.blog 中的 Java Bean,在沒有注解的情況下,會使用 Bean 的首字母小寫的非限定類名來作為它的別名, 比如 domain.blog.Author 的別名為 author;若有注解,則別名為其注解值,見下面的例子:


@Alias("author")
public class Author {
...
}

4、mappers:

例如: 用戶查找資源(包括 file:/// 形式的 URL)

<!-- 使用相對于類路徑的資源參考 -->
<mappers>
<mapper resource="org/mybatis/builder/AuthorMapper.xml"/>
<mapper resource="org/mybatis/builder/BlogMapper.xml"/>
<mapper resource="org/mybatis/builder/PostMapper.xml"/>
</mappers>
<!-- 使用完全限定資源定位符(URL) -->
<mappers>
<mapper url="file:///var/mappers/AuthorMapper.xml"/>
<mapper url="file:///var/mappers/BlogMapper.xml"/>
<mapper url="file:///var/mappers/PostMapper.xml"/>
</mappers>
<!-- 使用映射器介面實作類的完全限定類名 -->
<mappers>
<mapper />
<mapper />
<mapper />
</mappers>
<!-- 將包內的映射器介面實作全部注冊為映射器 -->
<mappers>
<package name="org.mybatis.builder"/>
</mappers>

5、生命周期和作用域

生命周期,和作用域,之至關重要的,因為錯誤的使用會導致非常嚴重的并發問題

SqlSessionFactoryBuilder:

一旦創建了SqlSessionFactory,就不再需要它了

定義區域變數、

SqlSessionFactory:

說白了就是可以想象為:資料庫連接池

一旦被創建就應該在應用的運行期間一直存在,沒有任何理由丟棄它或重新創建另一個實體

因此SqlSessionFactory的最佳作用域是應用作用域,

最簡單的就是使用單例模式或者靜態單例模式,

SqlSession:

連接到連接池的一個請求!

SqlSession的實體不是執行緒安全的,因此是不能被共享的,所以他的最佳作用域是請求或方法作用域,

用完之后需要趕緊關閉,否則資源被占用!

五、解決欄位名和屬性名不一致問題

package com.zeng.mybatis.pojo;

import org.apache.ibatis.type.Alias;

public class User {
private int id;
private String name;
private String password;

public User() {
}

public User(int id, String name, String password) {
this.id = id;
this.name = name;
this.password = password;
}

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 getPassword() {
return password;
}

public void setPassword(String pwd) {
this.password = pwd;
}

@Override
public String toString() {
return "User{" +
"id=" + id +
", name='" + name + '\'' +
", pwd='" + password + '\'' +
'}';
}
}

image-20230305140517015

這里可以看到資料庫的欄位名為pwd而物體類的屬性名為password

查詢結果:

image-20230305141231479

解決方法:

1、更改sql陳述句

沒改之前

<select id="getUserId" resultType="com.zeng.mybatis.pojo.User" parameterType="int">
select * from User where id = #{id}
</select>

改之后

<select id="getUserId" resultType="com.zeng.mybatis.pojo.User" parameterType="int">
select id,name,pwd as password from User where id = #{id}
</select>

image-20230305141352452

這里我們通過給欄位名取別名可以解決這個問題

2、使用resultMap
<?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.zeng.mybatis.dao.UserDao">
<resultMap id="userMap" type="com.zeng.mybatis.pojo.User">
<result property="id" column="id" />
<result property="name" column="name"/>
<result property="password" column="pwd"/>
</resultMap>

<select id="getUserId" resultMap="userMap">
select * from User where id = #{id}
</select>
</mapper>

image-20230305144259932

這里我們使用resultMap也能查詢出來

resultMap 元素是 MyBatis 中最重要最強大的元素,

六、日志工廠

logImpl指定 MyBatis 所用日志的具體實作,未指定時將自動查找,SLF4J | LOG4J | LOG4J2 | JDK_LOGGING | COMMONS_LOGGING | STDOUT_LOGGING | NO_LOGGING
     
1、STDOUT_LOGGING

只需要配置一些檔案即可:

<settings>
<setting name="logImpl" value="https://www.cnblogs.com/littlenoob/archive/2023/03/27/STDOUT_LOGGING"/>
</settings>

運行方法進行測驗:

image-20230306225905940

2、LOG4J
1、導包:
<!-- https://mvnrepository.com/artifact/log4j/log4j -->
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.17</version>
</dependency>
2、創建組態檔log4j.properties

#將等級為DEBUG的日志資訊輸出到console和file這兩個目的地,console和file的定義在下面的代碼 log4j.rootLogger=DEBUG,console,file

#控制臺輸出的相關設定 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=[%c]-%m%n

#檔案輸出的相關設定 log4j.appender.file = org.apache.log4j.RollingFileAppender log4j.appender.file.File=./log/logFile.log log4j.appender.file.MaxFileSize=10mb log4j.appender.file.Threshold=DEBUG log4j.appender.file.layout=org.apache.log4j.PatternLayout log4j.appender.file.layout.ConversionPattern=%p[%c]%m%n

#日志輸出級別 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

3、設定資源檔案
<settings>
<setting name="logImpl" value="https://www.cnblogs.com/littlenoob/archive/2023/03/27/LOG4J"/>
</settings>
4、使用Logger類
@Test
public void log4jTest(){
Logger logger = Logger.getLogger(daoTest.class);
logger.info("info:進入了log4jTest");
logger.error("error:進入了log4jTest");
logger.debug("debug:進入了log4jTest");
}

image-20230307133400960

image-20230307133414252

七、分頁

1、limit
1、介面
List<User> getUserLimit(Map<String, Integer> map);
2、介面對應的mapper
    <select id="getUserLimit" parameterType="map" resultMap="userMap">
select * from User limit #{start},#{end}
</select>
3、測驗類
@Test
public void getUserLimit(){
SqlSession sqlSession = MybatisUtils.getSqlSession();
UserDao mapper = sqlSession.getMapper(UserDao.class);
Map<String, Integer> limit = new HashMap<>();
limit.put("start",1);
limit.put("end",2);
List<User> userLimit = mapper.getUserLimit(limit);
for (User user : userLimit) {
System.out.println(user);
}
sqlSession.close();
}
4、結果

image-20230307150659006

2、RowBounds
1、介面
List<User> getUserRowBounds();
2、實作類
    <select id="getUserRowBounds" resultMap="userMap">
select * from User
</select>
3、測驗
@Test
public void getUserRowBounds(){
RowBounds rowBounds = new RowBounds(1,2);
SqlSession sqlSession = MybatisUtils.getSqlSession();
List<User> userList = sqlSession.selectList("com.zeng.mybatis.dao.UserDao.getUserRowBounds", null, rowBounds);
for (User user : userList) {
System.out.println(user);
}
sqlSession.close();
}
3、分頁工具

網址:https://pagehelper.github.io/

image-20230308224833973

八、使用注解開發

1、select查詢批量資料

1、介面
public interface UserDao {
@Select("select * from User")
List<User> getUserList();
}
2、核心xml配置

(使用注解的核心配置都在這里)

<mappers>
<mapper />
</mappers>

 

3、測驗
public class daoTest {
@Test
public void getUserList(){
SqlSession sqlSession = MybatisUtils.getSqlSession();
UserDao mapper = sqlSession.getMapper(UserDao.class);
List<User> userList = mapper.getUserList();
for (User user : userList) {
System.out.println(user);
}
sqlSession.close();
}
}

image-20230309175520890

2、select根據id查詢

1、介面
@Select("select * from User where id = #{uid}")
User getUserById(@Param("uid")int id);

這里的@Param注解是用與有多個基本型別的引數時加上,但是只要時基本資料型別建議都加上

2、測驗
@Test
public void getUserById(){
SqlSession sqlSession = MybatisUtils.getSqlSession();
UserDao mapper = sqlSession.getMapper(UserDao.class);
User userById = mapper.getUserById(1);
System.out.println(userById);
sqlSession.close();
}

image-20230309232742536

3、insert

1、介面
@Insert("insert into User (id,name,pwd) values(#{id},#{name},#{pwd})")
int addUser(User user);
2、測驗
@Test
public void addUser(){
SqlSession sqlSession = MybatisUtils.getSqlSession();
UserDao mapper = sqlSession.getMapper(UserDao.class);
mapper.addUser(new User(6, "趙云", "8520"));
sqlSession.close();
}

image-20230309233112996

4、update

1、介面
@Update("update User set name=#{name},pwd=#{pwd} where id=#{id}")
int updataUser(User user);
2、測驗
@Test
public void updataUser(){
SqlSession sqlSession = MybatisUtils.getSqlSession();
UserDao mapper = sqlSession.getMapper(UserDao.class);
mapper.updataUser(new User(5,"葉凡","987654321"));
sqlSession.close();
}

image-20230309232925009

5、delete

1、介面
@Delete("delete from User where id=#{id}")
int delete(@Param("id")int id);
2、測驗
@Test
public void deleteUser(){
SqlSession sqlSession = MybatisUtils.getSqlSession();
UserDao mapper = sqlSession.getMapper(UserDao.class);
mapper.delete(6);
sqlSession.close();
}

image-20230309233004366

九、Lombok

官方介紹:
Project Lombok is a java library that automatically plugs into your editor and build tools, spicing up your java.Never write another getter or equals method again, with one annotation your class has a fully featured builder, Automate your logging variables, and much more.

Project Lombok是一個java庫,可以自動插入編輯器和構建工具,為您的java增添趣味,永遠不要再寫另一個getter或equals方法,一個注釋你的類就有了一個功能齊全的構建器,自動化你的日志變數,等等,

1、IDEA中安裝Lombok插件

image-20230310232937212

里面的注解有:

@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
@StandardException
@val
@var
experimental @var
@UtilityClass

2、添加Maven依賴

<!-- https://mvnrepository.com/artifact/org.projectlombok/lombok -->
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.18.24</version>
<scope>provided</scope>
</dependency>

3、使用

package com.zeng.mybatis.pojo;

import lombok.*;

@EqualsAndHashCode //equals和hashcode方法
@ToString //toString方法
@AllArgsConstructor //所有屬性的有參構造方法
@NoArgsConstructor //無參構造方法
@Data //注解在類,生成setter/getter、equals、canEqual、hashCode、toString方法,如為final屬性,則不會為該屬性生成setter方法
@Getter //加在類上面就是所有屬性的get方法加在屬性上面可以生成單個get方法
@Setter //加在類上面就是所有屬性的set方法加在屬性上面可以生成單個set方法
public class User {
private int id;
private String name;
private String pwd;

}

上面的代碼等于下面的代碼

package com.zeng.mybatis.pojo;

public class User {
private int id;
private String name;
private String password;

public User() {
}

public User(int id, String name, String password) {
this.id = id;
this.name = name;
this.password = password;
}

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 getPassword() {
return password;
}

public void setPassword(String pwd) {
this.password = pwd;
}

@Override
public String toString() {
return "User{" +
"id=" + id +
", name='" + name + '\'' +
", pwd='" + password + '\'' +
'}';
}
}

十、多表查詢

1、多對一

1、第一種方式

1、物體類
package com.zeng.mybatis.pojo;

import lombok.Data;

@Data
public class Student {
private int id;
private String name;
private Teacher teacher;
}
package com.zeng.mybatis.pojo;

import lombok.Data;

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

 

2、介面
package com.zeng.mybatis.dao;

import com.zeng.mybatis.pojo.Student;

import java.util.List;

public interface studentMapper {
public List<Student> getStudent();
}
package com.zeng.mybatis.dao;

import com.zeng.mybatis.pojo.Teacher;

public interface teacherMapper {
public Teacher getTeacher(int id);
}
3、核心組態檔
<?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"></properties>
<!-- <typeAliases>
&lt;!&ndash;<typeAlias type="com.zeng.mybatis.pojo.User" alias="user"></typeAlias>&ndash;&gt;
<package name="com.zeng.mybatis.pojo"/>
</typeAliases>-->
<settings>
<setting name="logImpl" value="https://www.cnblogs.com/littlenoob/archive/2023/03/27/LOG4J"/>
</settings>

<environments default="development">
<environment id="development">
<transactionManager type="JDBC"/>
<dataSource type="POOLED">
<property name="driver" value="https://www.cnblogs.com/littlenoob/archive/2023/03/27/${driver}"/>
<property name="url" value="https://www.cnblogs.com/littlenoob/archive/2023/03/27/${jdbc.url}"/>
<property name="username" value="https://www.cnblogs.com/littlenoob/archive/2023/03/27/${username}"/>
<property name="password" value="https://www.cnblogs.com/littlenoob/archive/2023/03/27/${password}"/>
</dataSource>
</environment>
</environments>
<mappers>
<mapper />
<mapper />
</mappers>
</configuration>

特別注意

mapper是映射介面的時候和mapper映射檔案時的區別

介面映射時:
    <mappers>
<mapper />
<mapper />
</mappers>
mapper映射檔案
    <mappers>
<mapper />
<mapper />
</mappers>
4、介面映射檔案
<?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.zeng.mybatis.dao.studentMapper">

<select id="getStudent" resultMap="StudentTeacher">
select * from Student
</select>
<resultMap id="StudentTeacher" type="com.zeng.mybatis.pojo.Student">
<result property="id" column="id"/>
<result property="name" column="name"/>
<association property="teacher" column="tid" javaType="com.zeng.mybatis.pojo.Teacher" select="getTeacher"/>
</resultMap>
<select id="getTeacher" resultType="com.zeng.mybatis.pojo.Teacher">
select * from teacher where id = #{id}
</select>
</mapper>
5、測驗類
@Test
public void getStudentList(){
SqlSession sqlSession = MybatisUtils.getSqlSession();
studentMapper mapper = sqlSession.getMapper(studentMapper.class);
List<Student> student = mapper.getStudent();
for (Student s : student) {
System.out.println(s);
}
sqlSession.close();
}

2、按照結果嵌套查詢

1、介面
public List<Student> getStudent2();
2、介面映射檔案
<select id="getStudent2" resultMap="student2">
select s.id sid,s.name sname,t.name tname from student s,teacher t where s.tid = t.id
</select>
<resultMap id="student2" type="com.zeng.mybatis.pojo.Student">
<result property="id" column="sid"/>
<result property="name" column="sname"/>
<association property="teacher" javaType="com.zeng.mybatis.pojo.Teacher">
<result property="name" column="tname"/>
</association>
</resultMap>
3、測驗類
@Test
public void getStudentList2(){
SqlSession sqlSession = MybatisUtils.getSqlSession();
studentMapper mapper = sqlSession.getMapper(studentMapper.class);
List<Student> studentList = mapper.getStudent2();
for (Student student : studentList) {
System.out.println(student);
}
sqlSession.close();
}

image-20230312222326834

1、一對多

1、聯合查詢ResultMap映射

1、物體類

教師類

package com.mybatis.pojo;

import java.util.List;
public class teacher {
private int id;
private String name;
private List<student> students;

public teacher() {
}

public teacher(int id, String name, List<student> students) {
this.id = id;
this.name = name;
this.students = students;
}

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 List<student> getStudents() {
return students;
}

public void setStudents(List<student> students) {
this.students = students;
}

@Override
public String toString() {
return "teacher{" +
"id=" + id +
", name='" + name + '\'' +
", students=" + students +
'}';
}
}

學生類

package com.mybatis.pojo;

public class student {
private int id;
private String name;
private int tid;

public student() {
}

public student(int id, String name, int tid) {
this.id = id;
this.name = name;
this.tid = tid;
}

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 int getTid() {
return tid;
}

public void setTid(int tid) {
this.tid = tid;
}

@Override
public String toString() {
return "student{" +
"id=" + id +
", name='" + name + '\'' +
", tid=" + tid +
'}';
}
}
2、介面

教師介面

package com.mybatis.dao;

import com.mybatis.pojo.teacher;
import org.apache.ibatis.annotations.Param;

import java.util.List;

public interface teacherMapper {
public List<teacher> getAllTS(@Param("stid") int sid);
}

學生介面

package com.mybatis.dao;

import com.mybatis.pojo.student;

import java.util.List;

public interface studentMapper {
public List<student> getStudent();
}
3、核心組態檔
<?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"></properties>
<settings>
<setting name="logImpl" value="https://www.cnblogs.com/littlenoob/archive/2023/03/27/LOG4J"/>
</settings>

<environments default="development">
<environment id="development">
<transactionManager type="JDBC"/>
<dataSource type="POOLED">
<property name="driver" value="https://www.cnblogs.com/littlenoob/archive/2023/03/27/${driver}"/>
<property name="url" value="https://www.cnblogs.com/littlenoob/archive/2023/03/27/${jdbc.url}"/>
<property name="username" value="https://www.cnblogs.com/littlenoob/archive/2023/03/27/${username}"/>
<property name="password" value="https://www.cnblogs.com/littlenoob/archive/2023/03/27/${password}"/>
</dataSource>
</environment>
</environments>
<mappers>
<mapper resource="com/mybatis/dao/studentMapper.xml"/>
<mapper resource="com/mybatis/dao/teacherMapper.xml"/>
</mappers>
</configuration>
介面映射檔案

teacherMapper

<?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.mybatis.dao.teacherMapper">
<resultMap id="teacherMap" type="com.mybatis.pojo.teacher">
<result property="id" column="tid" />
<result property="name" column="tname"/>
<collection property="students" ofType="com.mybatis.pojo.student">
<result property="id" column="sid"/>
<result property="name" column="sname"/>
<result property="tid" column="stid"/>
</collection>
</resultMap>
<select id="getAllTS" resultMap="teacherMap">
select t.id tis,t.name tname,s.id sid,s.name sname from teacher t,student s where t.id = s.tid and t.id = #{stid}
</select>
</mapper>
4、測驗類
@org.junit.Test
public void getAllTS(){
SqlSession sqlSession = MybatisUtils.getSqlSession();
teacherMapper mapper = sqlSession.getMapper(teacherMapper.class);
List<teacher> allTS = mapper.getAllTS(1);
for (teacher teacher : allTS) {
System.out.println(teacher);
}
sqlSession.close();
}

image-20230314184421250

2、子查詢映射

1、介面
List<teacher> getTeacherS(@Param("tid") int tid);
2、介面映射檔案
<select id="getTeacherS" resultMap="teacherMaps">
select * from teacher where id=#{tid}
</select>
<resultMap id="teacherMaps" type="com.mybatis.pojo.teacher">
<collection property="students" javaType="ArrayList" ofType="com.mybatis.pojo.student" select="getStudents" column="id"/>
</resultMap>
<select id="getStudents" resultType="com.mybatis.pojo.student">
select * from student where tid=#{tid}
</select>
3、測驗類
@org.junit.Test
public void getTeacherS(){
SqlSession sqlSession = MybatisUtils.getSqlSession();
teacherMapper mapper = sqlSession.getMapper(teacherMapper.class);
List<teacher> teachers = mapper.getTeacherS(1);
for (teacher teacher : teachers) {
System.out.println(teacher);
}
sqlSession.close();
}

image-20230314205415941

十一、動態SQL

1、動態SQL環境搭建

1、創建資料庫
CREATE TABLE `blog` (
`id` VARCHAR(50) NOT NULL COMMENT '博客id',
`title` VARCHAR(100) NOT NULL COMMENT '博客標題',
`author` VARCHAR(30) NOT NULL COMMENT '博客作者',
`create_time` DATETIME NOT NULL COMMENT '創建時間',
`views` INT(30) NOT NULL COMMENT '瀏覽量'
)ENGINE=INNODB DEFAULT CHARSET=utf8;`blog`
2、創建物體類
package com.zeng.mybatis.pojo;

import lombok.Data;

import java.util.Date;
@Data
public class Blog {
private String id;
private String title;
private String author;
private Date create_time;
private int views;
}
3、db.properties
driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/mybatis?characterEncoding=utf-8&serverTimezone=UTC&useSSL=false
username=root
password=12345678
4、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="db.properties"></properties>
<settings>
<setting name="logImpl" value="https://www.cnblogs.com/littlenoob/archive/2023/03/27/LOG4J"/>
<setting name="mapUnderscoreToCamelCase" value="https://www.cnblogs.com/littlenoob/archive/2023/03/27/true"/>
</settings>

<environments default="development">
<environment id="development">
<transactionManager type="JDBC"/>
<dataSource type="POOLED">
<property name="driver" value="https://www.cnblogs.com/littlenoob/archive/2023/03/27/${driver}"/>
<property name="url" value="https://www.cnblogs.com/littlenoob/archive/2023/03/27/${jdbc.url}"/>
<property name="username" value="https://www.cnblogs.com/littlenoob/archive/2023/03/27/${username}"/>
<property name="password" value="https://www.cnblogs.com/littlenoob/archive/2023/03/27/${password}"/>
</dataSource>
</environment>
</environments>
<mappers>
<mapper />
</mappers>
</configuration>
5、工具類MybatisUtil
package com.zeng.mybatis.utils;

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;

public class MybatisUtils {
public static SqlSessionFactory sqlSessionFactory;
static {
try {
String resource = "mybatis-config.xml";
InputStream inputStream = Resources.getResourceAsStream(resource);
sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
} catch (IOException e) {
e.printStackTrace();
}


}
public static SqlSession getSqlSession(){
return sqlSessionFactory.openSession(true);
}
}
6、生成ID工具類IDUtil
package com.zeng.mybatis.utils;

import java.util.UUID;

public class IDUtil {
public static String getId(){
return UUID.randomUUID().toString().replaceAll("-","");
}
}

7、介面

package com.zeng.mybatis.dao;

import com.zeng.mybatis.pojo.Blog;

import java.util.List;

public interface BlogMapper {
int addBlog(Blog blog);

}
8、介面映射
<?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.zeng.mybatis.dao.BlogMapper">
<insert id="addBlog" parameterType="com.zeng.mybatis.pojo.Blog">
insert into blog (id,title,author,create_time,views) values (#{id},#{title},#{author},#{create_time},#{views})
</insert>
</mapper>
9、生成資料
package com.zeng.mybatis.dao;

import com.zeng.mybatis.pojo.Blog;
import com.zeng.mybatis.utils.IDUtil;
import com.zeng.mybatis.utils.MybatisUtils;
import org.apache.ibatis.session.SqlSession;

import java.util.Date;

public class Test {
@org.junit.Test
public void addtest(){
SqlSession sqlSession = MybatisUtils.getSqlSession();
BlogMapper mapper = sqlSession.getMapper(BlogMapper.class);
Blog blog = new Blog();
blog.setId(IDUtil.getId());
blog.setTitle("Mybatis學習");
blog.setAuthor("曾老師");
blog.setCreate_time(new Date());
blog.setViews(9000);
mapper.addBlog(blog);

Blog blog1 = new Blog();
blog1.setId(IDUtil.getId());
blog1.setTitle("java學習");
blog1.setAuthor("曾老師");
blog1.setCreate_time(new Date());
blog1.setViews(8000);
mapper.addBlog(blog1);

Blog blog2 = new Blog();
blog2.setId(IDUtil.getId());
blog2.setTitle("javaWeb學習");
blog2.setAuthor("曾老師");
blog2.setCreate_time(new Date());
blog2.setViews(100000);
mapper.addBlog(blog2);

Blog blog3 = new Blog();
blog3.setId(IDUtil.getId());
blog3.setTitle("單片機");
blog3.setAuthor("曾老師");
blog3.setCreate_time(new Date());
blog3.setViews(4000);
mapper.addBlog(blog3);

Blog blog4 = new Blog();
blog4.setId(IDUtil.getId());
blog4.setTitle("人工智能學習");
blog4.setAuthor("曾老師");
blog4.setCreate_time(new Date());
blog4.setViews(500);
mapper.addBlog(blog4);

Blog blog5 = new Blog();
blog5.setId(IDUtil.getId());
blog5.setTitle("大資料");
blog5.setAuthor("曾老師");
blog5.setCreate_time(new Date());
blog5.setViews(1500);
mapper.addBlog(blog5);
sqlSession.close();
}
}

2、IF標簽

1、介面
List<Blog> getBlogIF(Map map);
2、介面映射
<select id="getBlogIF" parameterType="map" resultType="com.zeng.mybatis.pojo.Blog">
select * from blog where 1=1
<if test="title != null">
and title = #{title}
</if>
</select>
3、測驗類
@org.junit.Test
public void getBlogIF(){
SqlSession sqlSession = MybatisUtils.getSqlSession();
BlogMapper mapper = sqlSession.getMapper(BlogMapper.class);
HashMap map = new HashMap<>();
map.put("title","單片機");
List<Blog> blogs = mapper.getBlogIF(map);
for (Blog blog : blogs) {
System.out.println(blog);
}
sqlSession.close();
}

image-20230316151911109

3、choose(when、otherwise)

1、介面
List<Blog> getBlogChoose(Map map);
2、介面映射
<select id="getBlogChoose" parameterType="map" resultType="com.zeng.mybatis.pojo.Blog">
select * from blog where 1=1
<choose>
<when test="title != null">
and title = #{title}
</when>
<when test="author != null">
and author = #{author}
</when>
<otherwise>
and views >= #{views}
</otherwise>
</choose>
</select>
3、測驗類
@org.junit.Test
public void getBlogChoose(){
SqlSession sqlSession = MybatisUtils.getSqlSession();
BlogMapper mapper = sqlSession.getMapper(BlogMapper.class);
HashMap Map = new HashMap<>();
Map.put("author","曾老師");
Map.put("views",8000);
List<Blog> blogs = mapper.getBlogChoose(Map);
for (Blog blog : blogs) {
System.out.println(blog);
}
sqlSession.close();
}

image-20230316164156787

4、trim(where、set)

1、where
1、介面
List<Blog> getBlogWhere(Map map);
2、介面映射
<select id="getBlogWhere" resultType="com.zeng.mybatis.pojo.Blog" parameterType="map">
select * from blog
<where>
<choose>
<when test="title != null">
title = #{title}
</when>
<when test="author != null">
and author = #{author}
</when>
</choose>
</where>
</select>
3、測驗類
@org.junit.Test
public void getBlogWhere(){
SqlSession sqlSession = MybatisUtils.getSqlSession();
BlogMapper mapper = sqlSession.getMapper(BlogMapper.class);
HashMap map = new HashMap<>();
map.put("title","人工智能學習");
List<Blog> blogs = mapper.getBlogWhere(map);
for (Blog blog : blogs) {
System.out.println(blog);
}
sqlSession.close();
}

image-20230316174940223

2、set
1、介面
int modifyBlogSet(Map map);

 

2、介面映射
<update id="modifyBlogSet" parameterType="map">
update blog
<set>
<if test="title != null">
title = #{title},
</if>
<if test="author != null">
author = #{author}
</if>
</set>
<where>
<if test="id != null">
id = #{id}
</if>
</where>
</update>

 

3、測驗類
@org.junit.Test
public void modifyBlog(){
SqlSession sqlSession = MybatisUtils.getSqlSession();
BlogMapper mapper = sqlSession.getMapper(BlogMapper.class);
HashMap map = new HashMap<>();
map.put("id","49aa2e7503434b86a33c527cf520e6a9");
map.put("title","單片機1");
map.put("author","超級大帥哥");
mapper.modifyBlogSet(map);
sqlSession.close();
}

image-20230316175912406

3、trim
1、介面
List<Blog> getBlogTrim(Map map);
2、介面映射
<select id="getBlogTrim" parameterType="map" resultType="com.zeng.mybatis.pojo.Blog">
select * from blog
<trim prefix="where" suffixOverrides="and | or">
<if test="title != null">
title = #{title}
</if>
<if test="author != null">
and author = #{author}
</if>
</trim>
</select>
3、測驗
@org.junit.Test
public void getBlogTrim(){
SqlSession sqlSession = MybatisUtils.getSqlSession();
BlogMapper mapper = sqlSession.getMapper(BlogMapper.class);
HashMap map = new HashMap<>();
map.put("title","單片機1");
map.put("author","超級大帥哥");
List<Blog> blogs = mapper.getBlogTrim(map);
for (Blog blog : blogs) {
System.out.println(blog);
}
sqlSession.close();
}

image-20230316212902611

十二、快取

1、快取簡介

快取(cache),原始意義是指訪問速度比一般隨機存取存盤器(RAM)快的一種高速存盤器,通常它不像系統主存那樣使用DRAM技術,而使用昂貴但較快速的SRAM技術,快取的設定是所有現代計算機系統發揮高性能的重要因素之一,

1、什么是快取?

存在記憶體中的臨時資料

將用戶經常查詢的資料放在快取(記憶體)中,用戶去查詢資料就不用從磁盤上(關系型資料庫資料檔案)查詢,從快取中查詢,從而提高查詢效率,解決了高并發系統的性能問題

2、為什么使用快取?

減少和資料庫的互動次數,減少系統開銷,提高系統效率

3、什么樣的資料能使用快取?

經常查詢并且不經常改變的資料

2、一級快取

一級快取也叫本地快取:Sqlsession

與資料庫同一次會話期間查詢到的資料會放在本地快取中

以后如果需要獲取相同的資料,直接從快取中拿,沒必要再去查詢資料庫

測驗步驟:

1、開啟日志!

匯入log4j依賴

<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.12</version>
<scope>test</scope>
</dependency>

配置日志檔案


log4j.rootLogger=DEBUG,console,file


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=[%c]-%m%n


log4j.appender.file = org.apache.log4j.RollingFileAppender
log4j.appender.file.File=./log/logFile.log
log4j.appender.file.MaxFileSize=10mb
log4j.appender.file.Threshold=DEBUG
log4j.appender.file.layout=org.apache.log4j.PatternLayout
log4j.appender.file.layout.ConversionPattern=[%p][%d{yy-MM-dd}][%c]%m%n


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
2、測驗在一個Session中查詢兩次相同記錄
@Test
public void getUserById(){
SqlSession sqlSession = MybatisUtils.getSqlSession();
userMapper mapper = sqlSession.getMapper(userMapper.class);
user user = mapper.getUserById(1);
System.out.println(user);
System.out.println("<==========================================================>");
user user2 = mapper.getUserById(1);
System.out.println(user2);
sqlSession.close();
}
3、查看日志輸出

image-20230320224944373

可以清楚的看見只運行了一次sql陳述句

快取失效的情況:

1、查詢不同的東西

這里分別查詢id為1和2的兩條記錄

@Test
public void getUserById(){
SqlSession sqlSession = MybatisUtils.getSqlSession();
userMapper mapper = sqlSession.getMapper(userMapper.class);
user user = mapper.getUserById(1);
System.out.println(user);
System.out.println("<==========================================================>");
user user2 = mapper.getUserById(2);
System.out.println(user2);
sqlSession.close();
}

image-20230320225241568

這里可以看見運行了兩次sql陳述句

2、增刪改操作,可能會改變原來的資料,所以必定會重繪快取!

這里我們更改了第一條記錄,并且對id為1的記錄查詢兩次

@Test
public void getUserById(){
SqlSession sqlSession = MybatisUtils.getSqlSession();
userMapper mapper = sqlSession.getMapper(userMapper.class);
user user = mapper.getUserById(1);
System.out.println(user);
System.out.println("<==========================================================>");
user setUser = new user();
setUser.setId(1);
setUser.setName("張三(改)");
setUser.setPwd("8520");
mapper.updateUser(setUser);
System.out.println("<==========================================================>");
user user1 = mapper.getUserById(1);
System.out.println(user1);
sqlSession.close();
}

image-20230320230405629

這里可以清楚的看見在第一次查詢過后,對記錄進行更改,然后再次查詢也會再執行一次sql陳述句,所以我們在執行增刪改的時候會更新資料,因此會重新連接查詢

3、查詢不同的Mapper.xml
4、手動清除快取

這里我們使用clearCache()方法來手動清除快取

@Test
public void getUserById(){
SqlSession sqlSession = MybatisUtils.getSqlSession();
userMapper mapper = sqlSession.getMapper(userMapper.class);
user user = mapper.getUserById(1);
System.out.println(user);
System.out.println("<==========================================================>");
sqlSession.clearCache();//手動清楚快取
user user1 = mapper.getUserById(1);
System.out.println(user1);
sqlSession.close();
}

image-20230320230829576

這里我們可以看到在使用clearCache()方法,手動清除快取后就會對資料就行第二次連接查詢

3、二級快取

二級快取也叫全域快取,一級快取作用域太低,所以誕生了二級快取

基于namespace級別的快取,一個名稱空間,對應一個二級快取

作業機制

一個會話查詢一條資料,這個資料就會被放在當前會話的一級快取中;

如果當前會話關閉了,這個會話對應的一級快取就沒了;但是我們想要的是,會話關閉了,一級快取中的資料會被保存到二級快取中;

新的會話查詢資訊,就可以從二級快取中獲取內容;

不同的mapper查出的資料會放在自己對應的快取(map)中

步驟:

1、開啟全域快取
<settings>
<!--開啟二級快取-->
<setting name="cacheEnabled" value="https://www.cnblogs.com/littlenoob/archive/2023/03/27/true"/>
</settings>
2、在要使用二級快取的Mapper中開啟
<cache/>

直接加一個<cache/>標簽就可以開啟二級快取了

<cache
eviction="FIFO"
flushInterval="60000"
size="512"
readOnly="true"/>

當然里面可以配置各種引數,引數可以自行配置

3、測驗
@Test
public void getUserById(){
SqlSession sqlSession = MybatisUtils.getSqlSession();
SqlSession sqlSession2 = MybatisUtils.getSqlSession();

userMapper mapper = sqlSession.getMapper(userMapper.class);
user user = mapper.getUserById(2);
System.out.println(user);

sqlSession.close();
System.out.println("<======================================================================>");

userMapper mapper2 = sqlSession2.getMapper(userMapper.class);
user user1 = mapper2.getUserById(2);
System.out.println(user1);


sqlSession2.close();
}

問題

org.apache.ibatis.cache.CacheException: Error serializing object.  Cause: java.io.NotSerializableException: com.mybatis.pojo.user

沒有引數就要序列化物體類

image-20230321160743857

可以看出在會話一關閉后,資料就存入了二級快取,所有第二次查詢相同資料的時候沒有走資料庫,而是直接在二級快取中取出

 

只要開啟了二級快取,在同一個Mapper下就有效

所有的資料都會先放在一級快取中;

只有當會話提交,或者關閉的時候,才會提交到二級緩沖中!

4、快取原理

一級快取是SqlSession級別的快取,默認開啟,不同的sqlSession之間的快取資料區域(HashMap)是互相不影響的,

二級快取是mapper級別的快取,基于mapper檔案的namespace,多個SqlSession去操作同一個Mapper的sql陳述句,多個SqlSession可以共用二級快取,二級快取是跨SqlSession的,

image-20230323234423101

一級快取先在資料庫中查詢資料,然后存入二級快取中,如果二級快取中沒有再從資料庫中查找

5、Ehcahe

什么是EhCache?

EhCache 是一個純Java的行程內快取框架,具有快速、精干等特點,是Hibernate中默認的CacheProvider,他和mybatis當中的二級快取唯一的區別就是,他是存盤于硬碟當中的,也就是他是可以用來做分布式快取的,

 

轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/548328.html

標籤:其他

上一篇:【Visual Leak Detector】配置項 AggregateDuplicates

下一篇:【Visual Leak Detector】配置項 ForceIncludeModulesmd

標籤雲
其他(157675) Python(38076) JavaScript(25376) Java(17977) C(15215) 區塊鏈(8255) C#(7972) AI(7469) 爪哇(7425) MySQL(7132) html(6777) 基礎類(6313) sql(6102) 熊猫(6058) PHP(5869) 数组(5741) R(5409) Linux(5327) 反应(5209) 腳本語言(PerlPython)(5129) 非技術區(4971) Android(4554) 数据框(4311) css(4259) 节点.js(4032) C語言(3288) json(3245) 列表(3129) 扑(3119) C++語言(3117) 安卓(2998) 打字稿(2995) VBA(2789) Java相關(2746) 疑難問題(2699) 细绳(2522) 單片機工控(2479) iOS(2429) ASP.NET(2402) MongoDB(2323) 麻木的(2285) 正则表达式(2254) 字典(2211) 循环(2198) 迅速(2185) 擅长(2169) 镖(2155) 功能(1967) .NET技术(1958) Web開發(1951) python-3.x(1918) HtmlCss(1915) 弹簧靴(1913) C++(1909) xml(1889) PostgreSQL(1872) .NETCore(1853) 谷歌表格(1846) Unity3D(1843) for循环(1842)

熱門瀏覽
  • 【C++】Microsoft C++、C 和匯編程式檔案

    ......

    uj5u.com 2020-09-10 00:57:23 more
  • 例外宣告

    相比于斷言適用于排除邏輯上不可能存在的狀態,例外通常是用于邏輯上可能發生的錯誤。 例外宣告 Item 1:當函式不可能拋出例外或不能接受拋出例外時,使用noexcept 理由 如果不打算拋出例外的話,程式就會認為無法處理這種錯誤,并且應當盡早終止,如此可以有效地阻止例外的傳播與擴散。 示例 //不可 ......

    uj5u.com 2020-09-10 00:57:27 more
  • Codeforces 1400E Clear the Multiset(貪心 + 分治)

    鏈接:https://codeforces.com/problemset/problem/1400/E 來源:Codeforces 思路:給你一個陣列,現在你可以進行兩種操作,操作1:將一段沒有 0 的區間進行減一的操作,操作2:將 i 位置上的元素歸零。最終問:將這個陣列的全部元素歸零后操作的最少 ......

    uj5u.com 2020-09-10 00:57:30 more
  • UVA11610 【Reverse Prime】

    本人看到此題沒有翻譯,就附帶了一個自己的翻譯版本 思考 這一題,它的第一個要求是找出所有 $7$ 位反向質數及其質因數的個數。 我們應該需要質數篩篩選1~$10^{7}$的所有數,這里就不慢慢介紹了。但是,重讀題,我們突然發現反向質數都是 $7$ 位,而將它反過來后的數字卻是 $6$ 位數,這就說明 ......

    uj5u.com 2020-09-10 00:57:36 more
  • 統計區間素數數量

    1 #pragma GCC optimize(2) 2 #include <bits/stdc++.h> 3 using namespace std; 4 bool isprime[1000000010]; 5 vector<int> prime; 6 inline int getlist(int ......

    uj5u.com 2020-09-10 00:57:47 more
  • C/C++編程筆記:C++中的 const 變數詳解,教你正確認識const用法

    1、C中的const 1、區域const變數存放在堆疊區中,會分配記憶體(也就是說可以通過地址間接修改變數的值)。測驗代碼如下: 運行結果: 2、全域const變數存放在只讀資料段(不能通過地址修改,會發生寫入錯誤), 默認為外部聯編,可以給其他源檔案使用(需要用extern關鍵字修飾) 運行結果: ......

    uj5u.com 2020-09-10 00:58:04 more
  • 【C++犯錯記錄】VS2019 MFC添加資源不懂如何修改資源宏ID

    1. 首先在資源視圖中,添加資源 2. 點擊新添加的資源,復制自動生成的ID 3. 在解決方案資源管理器中找到Resource.h檔案,編輯,使用整個專案搜索和替換的方式快速替換 宏宣告 4. Ctrl+Shift+F 全域搜索,點擊查找全部,然后逐個替換 5. 為什么使用搜索替換而不使用屬性視窗直 ......

    uj5u.com 2020-09-10 00:59:11 more
  • 【C++犯錯記錄】VS2019 MFC不懂的批量添加資源

    1. 打開資源頭檔案Resource.h,在其中預先定義好宏 ID(不清楚其實ID值應該設定多少,可以先新建一個相同的資源項,再在這個資源的ID值的基礎上遞增即可) 2. 在資源視圖中選中專案資源,按F7編輯資源檔案,按 ID 型別 相對路徑的形式添加 資源。(別忘了先把檔案拷貝到專案中的res檔案 ......

    uj5u.com 2020-09-10 01:00:19 more
  • C/C++編程筆記:關于C++的參考型別,專供新手入門使用

    今天要講的是C++中我最喜歡的一個用法——參考,也叫別名。 參考就是給一個變數名取一個變數名,方便我們間接地使用這個變數。我們可以給一個變數創建N個參考,這N + 1個變數共享了同一塊記憶體區域。(參考型別的變數會占用記憶體空間,占用的記憶體空間的大小和指標型別的大小是相同的。雖然參考是一個物件的別名,但 ......

    uj5u.com 2020-09-10 01:00:22 more
  • 【C/C++編程筆記】從頭開始學習C ++:初學者完整指南

    眾所周知,C ++的學習曲線陡峭,但是花時間學習這種語言將為您的職業帶來奇跡,并使您與其他開發人員區分開。您會更輕松地學習新語言,形成真正的解決問題的技能,并在編程的基礎上打下堅實的基礎。 C ++將幫助您養成良好的編程習慣(即清晰一致的編碼風格,在撰寫代碼時注釋代碼,并限制類內部的可見性),并且由 ......

    uj5u.com 2020-09-10 01:00:41 more
最新发布
  • Rust中的智能指標:Box<T> Rc<T> Arc<T> Cell<T> RefCell<T> Weak

    Rust中的智能指標是什么 智能指標(smart pointers)是一類資料結構,是擁有資料所有權和額外功能的指標。是指標的進一步發展 指標(pointer)是一個包含記憶體地址的變數的通用概念。這個地址參考,或 ” 指向”(points at)一些其 他資料 。參考以 & 符號為標志并借用了他們所 ......

    uj5u.com 2023-04-20 07:24:10 more
  • Java的值傳遞和參考傳遞

    值傳遞不會改變本身,參考傳遞(如果傳遞的值需要實體化到堆里)如果發生修改了會改變本身。 1.基本資料型別都是值傳遞 package com.example.basic; public class Test { public static void main(String[] args) { int ......

    uj5u.com 2023-04-20 07:24:04 more
  • [2]SpinalHDL教程——Scala簡單入門

    第一個 Scala 程式 shell里面輸入 $ scala scala> 1 + 1 res0: Int = 2 scala> println("Hello World!") Hello World! 檔案形式 object HelloWorld { /* 這是我的第一個 Scala 程式 * 以 ......

    uj5u.com 2023-04-20 07:23:58 more
  • 理解函式指標和回呼函式

    理解 函式指標 指向函式的指標。比如: 理解函式指標的偽代碼 void (*p)(int type, char *data); // 定義一個函式指標p void func(int type, char *data); // 宣告一個函式func p = func; // 將指標p指向函式func ......

    uj5u.com 2023-04-20 07:23:52 more
  • Django筆記二十五之資料庫函式之日期函式

    本文首發于公眾號:Hunter后端 原文鏈接:Django筆記二十五之資料庫函式之日期函式 日期函式主要介紹兩個大類,Extract() 和 Trunc() Extract() 函式作用是提取日期,比如我們可以提取一個日期欄位的年份,月份,日等資料 Trunc() 的作用則是截取,比如 2022-0 ......

    uj5u.com 2023-04-20 07:23:45 more
  • 一天吃透JVM面試八股文

    什么是JVM? JVM,全稱Java Virtual Machine(Java虛擬機),是通過在實際的計算機上仿真模擬各種計算機功能來實作的。由一套位元組碼指令集、一組暫存器、一個堆疊、一個垃圾回收堆和一個存盤方法域等組成。JVM屏蔽了與作業系統平臺相關的資訊,使得Java程式只需要生成在Java虛擬機 ......

    uj5u.com 2023-04-20 07:23:31 more
  • 使用Java接入小程式訂閱訊息!

    更新完微信服務號的模板訊息之后,我又趕緊把微信小程式的訂閱訊息給實作了!之前我一直以為微信小程式也是要企業才能申請,沒想到小程式個人就能申請。 訊息推送平臺🔥推送下發【郵件】【短信】【微信服務號】【微信小程式】【企業微信】【釘釘】等訊息型別。 https://gitee.com/zhongfuch ......

    uj5u.com 2023-04-20 07:22:59 more
  • java -- 緩沖流、轉換流、序列化流

    緩沖流 緩沖流, 也叫高效流, 按照資料型別分類: 位元組緩沖流:BufferedInputStream,BufferedOutputStream 字符緩沖流:BufferedReader,BufferedWriter 緩沖流的基本原理,是在創建流物件時,會創建一個內置的默認大小的緩沖區陣列,通過緩沖 ......

    uj5u.com 2023-04-20 07:22:49 more
  • Java-SpringBoot-Range請求頭設定實作視頻分段傳輸

    老實說,人太懶了,現在基本都不喜歡寫筆記了,但是網上有關Range請求頭的文章都太水了 下面是抄的一段StackOverflow的代碼...自己大修改過的,寫的注釋挺全的,應該直接看得懂,就不解釋了 寫的不好...只是希望能給視頻網站開發的新手一點點幫助吧. 業務場景:視頻分段傳輸、視頻多段傳輸(理 ......

    uj5u.com 2023-04-20 07:22:42 more
  • Windows 10開發教程_編程入門自學教程_菜鳥教程-免費教程分享

    教程簡介 Windows 10開發入門教程 - 從簡單的步驟了解Windows 10開發,從基本到高級概念,包括簡介,UWP,第一個應用程式,商店,XAML控制元件,資料系結,XAML性能,自適應設計,自適應UI,自適應代碼,檔案管理,SQLite資料庫,應用程式到應用程式通信,應用程式本地化,應用程式 ......

    uj5u.com 2023-04-20 07:22:35 more