环境:
JDK1.8
Mysql 5.7
maven3.9.1
IDEA
回顾:
JDBC
Mysql
java基础
Maven
Junit (单元测试)
SSM框架:配置文件,
官网文档 : https://mybatis.org/mybatis-3/zh/index.html
1、简介
1.1、什么是Mybatis
1、MyBatis 是一款优秀的持久层框架。
2、它支持自定义 SQL、存储过程以及高级映射。
3、MyBatis 免除了几乎所有的 JDBC 代码以及设置参数和获取结果集
4、MyBatis 可以通过简单的 XML 或注解来配置和映射原始类型、接口 和 Java POJO(Plain Old Java Objects,普通老式 Java 对象)为数据库中的记录。
5、MyBatis本是apache的一个开源项目iBatis,2010年这个项目由apache software foundation迁移到了google code,并且改名为MyBatis。2013年11月迁移到Github。
如何获得mybatis?
maven仓库:https://mvnrepository.com/search?q=spring
<!-- https://mvnrepository.com/artifact/org.mybatis/mybatis -->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.5.9</version>
</dependency>
Github地址: https://github.com/mybatis/mybatis-3/releases/tag/mybatis-3.5.13
1.2、持久化
数据持久化
。持久化就是程序的数据在持久状态和瞬时状态转化的过程
。内存:断电即失
。数据库(jdbc),io文件持久化。
。生活:冷藏,罐头。
为什么需要持久化?
有一些对象,不能让他丢掉。
内存太贵了
1.3、持久层
Dao层,Service层,Contrlle层…
。 完成持久化工作的代码块
。层界限十分明显
1.4、为什么需要Mybatis?
。帮助程序员将数据存入数据库中
。方便
。传统的JDBC代码太复杂了,简化。框架。自动化
。不用Mybatis也可以,更容易上手。技术没有高低之分
优点:
。简单易学
。灵活
。sql和代码的分离,提高了可维护性。
。提供映射标签,支持对象与数据库的ORM字段关系映射。
。提供对象关系映射标签,支持对象关系组建维护。
。提供xml标签,支持编写动态sql。
最重要的一点:使用的人多!
2、第一个Mybatis程序
思路:搭建环境–>导入Mybatis–>编写代码–>测试
2.1、搭建环境
搭建数据库
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,'狂神','123456'),
(2,'利利','235566'),
(3,'张三','232656'),
(4,'李四','321556'),
(5,'王五','456789')
新建项目
1、新建一个普通的maven项目
2、删除src目录
3、导入maven依赖
<!--导入依赖-->
<dependencies>
<!--mysql驱动-->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.47</version>
</dependency>
<!--mybatis-->
<!-- https://mvnrepository.com/artifact/org.mybatis/mybatis -->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.5.9</version>
</dependency>
<!--junit-->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
</dependency>
</dependencies>
2.2、创建一个模块
编写mybatis的核心配置文件
在子项目里src / resources目录下新建xml文件
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration
PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"https://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?userSSL=true&useUnicode=true&charcterEncoding=UTF-8"/>
<property name="username" value="root"/>
<property name="password" value="123456"/>
</dataSource>
</environment>
</environments>
</configuration>
编写mybatis的工具类
//SqlSessionFactory-->sqlSession
public class MybatisUtils {
private static SqlSessionFactory sqlSessionFactory;
static {
try {
//使用Mybatis第一步:获取SqlSessionFactory对象
String resource = "mybatis-config.xml";
InputStream inputStream = Resources.getResourceAsStream(resource);
sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
} catch (IOException e) {
e.printStackTrace();
}
}
//既然有了 SqlSessionFactory,顾名思义,我们可以从中获得 SqlSession 的实例。
// SqlSession 提供了在数据库执行 SQL 命令所需的所有方法。
public static SqlSession getSqlsession(){
// SqlSession sqlSession = sqlSessionFactory.openSession();
// return sqlSession;
// 前两行代码优化后
return sqlSessionFactory.openSession();
}
2.3、编写代码
实体类
//实体类
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 + '\'' +
'}';
}
}
Dao接口
public interface UserDao {
List<User> getUserList();
}
接口实现类由原来的UserDaoImpl转变为一个Mapper配置文件
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"https://mybatis.org/dtd/mybatis-3-mapper.dtd">
<!--namespace=绑定一个对应的Dao/Mapper接口-->
<mapper namespace="com.kuang.dao.UserDao">
<!--select查询语句 -->
<select id="getUserList" resultType="com.kuang.pojo.User">
select * from mybatis.user;
</select>
</mapper>
注意:
1、mapper namespace 接口绑定不要出错
2、resultType 返回类型不要写错
3、select id 名字不要写错
2.4、测试
注意点:mapper未绑定出错
org.apache.ibatis.binding.BindingException: Type interface com.kuang.dao.UserDao is not known to the MapperRegistry.
MapperRegistry是什么?
核心配置文件中注册mappers
junit测试
public class UserDaoTest {
@Test
public void test(){
//第一步:获取sqlsession对象
SqlSession sqlsession = MybatisUtils.getSqlsession();
//方式一:getMapper
UserDao userDao = sqlsession.getMapper(UserDao.class);
List<User> userList = userDao.getUserList();
for (User user : userList) {
System.out.println(user);
}
//关闭sqlSession
sqlsession.close();
}
}
测试中可能会遇到的问题:
1、配置文件没有注册
2、绑定接口错误
<!--每一个Mapper.XML都需要在Mybatis的核心配置文件中注册! -->
<mappers>
<mapper resource="com/kuang/dao/UserMapper.xml"/>
</mappers>
3、方法名不对
4、返回类型不对
5、Maven导出资源问题
maven由于他的约定大于配置,我们之后可以能遇到我们写的配置文件,无法被导出或者生效的问题,解决方案:
在当前pom.xml下增加
<!--在build中配置resources,来防止我们的资源导出失败的问题-->
<build>
<resources>
<!-- 设置正常情况的resources目录下的properties文件-->
<resource>
<!-- 配置路径-->
<directory>src/main/resources</directory>
<includes>
<!-- 包含什么文件-->
<include>**/*.properties</include>
<include>**/*.xml</include>
</includes>
<filtering>true</filtering>
</resource>
<!-- 设置java路径的properties文件-->
<resource>
<directory>src/main/java</directory>
<includes>
<include>**/*.properties</include>
<include>**/*.xml</include>
</includes>
<filtering>true</filtering>
</resource>
</resources>
</build>
配置完后重新生成一下
按以下顺序七步完成
3、CRUD
1、namespace
namespace中的包名和 Dao/Mpper 接口的包名一致!
2、select
选择,查询语句;
id:就是对应的namespace中的方法名
resultType:Sql语句执行的返回值!
parameterType:参数类型!
1、编写接口
//查询全部用户
List<User> getUserList();
2、编写对应的mapper中的sql语句
<select id="getUserById" parameterType="int" resultType="com.kuang.pojo.User">
select *from mybatis.user where id = #{id}
</select>
3、测试
@Test
public void getUserById(){
SqlSession sqlsession = MybatisUtils.getSqlsession();
UserMapper mapper = sqlsession.getMapper(UserMapper.class);
User user = mapper.getUserById(1);
System.out.println(user);
sqlsession.close();
}
3、Insert
<insert id="addUser" parameterType="com.kuang.pojo.User">
insert into mybatis.user(id,name,pwd) values(#{id},#{name},#{pwd});
</insert>
4、update
<update id="updateUser" parameterType="com.kuang.pojo.User">
update mybatis.user set name =#{name},pwd=#{pwd} where id =#{id};
</update>
5、Delete
<delete id="deleteUser" parameterType="int">
delete from mybatis.user where id =#{id};
</delete>
注意点:增删改需要提交事务
6、分析错误
标签不要匹配错
resource绑定mapper,需要使用路径
程序配置文件必须符合规范
NullPointerException,没有注册到资源
输入的xml文件中存在中文乱码问题
maven资源没有导出问题
7、万能Map
假设,我们的实体类,或者数据库中的表,字段或者参数过多,我们应当考虑使用Map
//万能的map
int addUser2(Map<String,Object> map);
<!--对象中的属性,可以直接取出来
传递map的key
-->
<insert id="addUser2" parameterType="map">
insert into mybatis.user(id,pwd) values(#{userid},#{password});
</insert>
@Test
public void addUser2(){
SqlSession sqlsession = MybatisUtils.getSqlsession();
UserMapper mapper = sqlsession.getMapper(UserMapper.class);
Map<String, Object> map = new HashMap<String, Object>();
map.put("userid",25);
map.put("userName","hello");
map.put("userpassword","12333333");
mapper.addUser2(map);
sqlsession.close();
}
Map传递参数,直接在sql中取key即可!【parameterType=“map”】
对象传递参数,直接在sql中取对象的属性即可!【parameterType=“Object”】
只有一个基本类型参数的情况下,可以直接在sql中取到!
多个参数用Map,或者注解!
8、模糊查询
模糊查询怎么写?
1、java代码执行的时候,传递通配符% %
List<User> userList = mapper.getUserLike("%李%");
2、在sql拼接中使用通配符!
select * from mybatis.user where name like "%"#{value}"%"
4、配置解析
1、核心配置文件
mybatis-config.xml
MyBatis 的配置文件包含了会深深影响 MyBatis 行为的设置和属性信息。
configuration(配置)
properties(属性)
settings(设置)
typeAliases(类型别名)
typeHandlers(类型处理器)
objectFactory(对象工厂)
plugins(插件)
environments(环境配置)
environment(环境变量)
transactionManager(事务管理器)
dataSource(数据源)
databaseIdProvider(数据库厂商标识)
mappers(映射器)
2、环境配置(environments)
MyBatis 可以配置成适应多种环境,不过要记住:尽管可以配置多个环境,但每个 SqlSessionFactory 实例只能选择一种环境。
mybatis默认的事务管理器是JDBC,连接池 :POOLED
3、属性(properties)
我们可以通过properties属性来实现引用配置文件。
这些属性都是可外部配置且可动态替换。既可以在典型的 Java 属性文件中配置,可以在 properties 元素的子元素中设置。
编写一个配置文件
db.properties
driver=com.mysql.jdbc.Driver
url=jdbc:mysql://localhost:3306/mybatis?useSSL=false&useUnicode=true&characterEncoding=UTF-8
username=root
password=123456
xml文件中注释快捷键:
注释:CTRL + SHIFT + /
撤销注释:CTRL + SHIFT + \
在核心配置文件中引入
<!--引入外部配置文件-->
<properties resource="db.properties">
<property name="username" value="root"/>
<property name="password" value="111111"/>
</properties>
1、可以直接引入外部文件
2、可以在其中增加一些属性配置
3、如果两个文件有同一字段优先使用外部配置文件的!
4、类型别名(typeAliases)
类型别名可为 Java 类型设置一个缩写名字。
它仅用于 XML 配置,意在降低冗余的全限定类名书写。
```xml
<!--可以给实体类起别名-->
<typeAliases>
<typeAlias type="com.kuang.pojo.User" alias="User"/>
</typeAliases>
也可以指定一个包名,MyBatis 会在包名下面搜索需要的 Java Bean,比如:
扫描实体类的包,他的默认别名就为这个类的类名,首字母小写!。
<!--可以给实体类起别名-->
<typeAliases>
<package name="com.kuang.pojo"/>
</typeAliases>
在实体类少的时候用第一种方式。
如果实体类十分多,建议使用第二种。
第一种可以DIY(自定义)别名,第二种则不行,如果非要改,需要在实体类上增加注解。
@Alias("user")
//实体类
public class User {
5、设置
这是mybatis中极为重要的调整设置,他们会改变Mybatis的运行时行为。
6、其他设置
typeHandlers(类型处理器)
objectFactory(对象工厂)
plugins(插件)
。mybatias-generator-core
。mybatis-plus
。通用mapper
7、映射器(mappers)
MapperRegistry:注册绑定我们的mapper文件。
方式一:
<!--每一个Mapper.XML都需要在Mybatis的核心配置文件中注册! -->
<mappers>
<mapper resource="com/kuang/dao/UserMapper.xml"/>
</mappers>
方式二:使用Class文件绑定注册
<mappers>
<mapper class="com.kuang.dao.UserMapper"/>
</mappers>
注意点:
接口和他的Mapper配置文件必须同名
接口和他的Mapper配置文件必须在同一目录下
方式三:使用扫描包进行注入绑定
<mappers>
<package name="com.kuang.dao"/>
</mappers>
注意点:
接口和他的Mapper配置文件必须同名
接口和他的Mapper配置文件必须在同一目录下
8、作用域(Scope)和生命周期
不同作用域和生命周期类别是至关重要的,因为错误的使用会导致非常严重的并发问题。
1、SqlSessionFactoryBuilder:
。一旦创建了 SqlSessionFactory,就不再需要它了
。局部变量
2、SqlSessionFactory
。说白了就是可以想象为:数据库连接池
。SqlSessionFactory 一旦被创建就应该在应用的运行期间一直存在, 没有任何理由丢弃它或重新创建另一个实例
。因此 SqlSessionFactory 的最佳作用域是应用作用域(程序开始他就开始,程序结束他就结束)
。最简单的就是使用单例模式或者静态单例模式。
3、SqlSession
。想象成连接到连接池的一个请求!
。SqlSession 的实例不是线程安全的,因此是不能被共享的,所以它的最佳的作用域是请求或方法作用域
。用完之后需要赶紧关闭,否则资源被占用!
这里面的每一个Mapper,就代表一个具体的业务!
5、解决属性名和字段名不一致的问题
数据库中的字段
新建一个项目或拷贝之前的,测试实体类字段不一致的情况
public class User {
private int id;
private String name;
private String password;
1、测试出现问题
select *from mybatis.user where id = #{id}
-- 类型处理器
select id,name,pwd as password from mybatis.user where id = #{id}
解决方法:
1、起别名
select id,name,pwd as password from mybatis.user where id = #{id}
2、resultMap
结果集映射
id name pwd
id name password
<resultMap id="UserMap" type="User">
<!--column数据库中的字段,property实体类中的属性-->
<result column="id" property="id"/>
<result column="name" property="name"/>
<result column="pwd" property="password"/>
</resultMap>
<select id="getUserByID" resultMap="UserMap">
select *from mybatis.user where id = #{id}
</select>
resultMap 元素是 MyBatis 中最重要最强大的元素。
ResultMap 的设计思想是,对简单的语句做到零配置,对于复杂一点的语句,只需要描述语句之间的关系就行了。
ResultMap 的优秀之处——你完全可以不用显式地配置它们。
如果这个世界总是这么简单就好了。
6、日志
6.1、日志工厂
如果一个数据库操作,出现了异常,我们需要排错。日志工厂就是最好的帮手!
曾经:sout ,debug
现在:日志工厂!
SLF4J
LOG4J(3.5.9 起废弃)
LOG4J2
JDK_LOGGING
COMMONS_LOGGING
STDOUT_LOGGING【掌握】
NO_LOGGING
在Mybatis中具体使用哪一个日志实现,在设置中设定!
STDOUT_LOGGING标准日志输出
在mybatis核心配置文件中,配置我们的日志!
<settings>
<setting name="logImpl" value="STDOUT_LOGGING"/>
</settings>
注意点:
1、在核心配置文件中位置是固定的
2、name 和 value 大小写一定要和官网一样
3、不能出现多余空格,会报错。
7、分页
思考:为什么要分页?
减少数据的处理量
7.1、使用limit分页
SELECT *FROM user limit startIndex ,pageSize;
select * from user limit 4;#[0,n]
使用mabatis实现分页,核心就是SQL
1、接口
//分页
List<User> getUserByLimit(Map<String,Integer> map);
2、Mappertaining.XLM
<!--分页-->
<select id="getUserByLimit" parameterType="map" resultMap="UserMap">
select * from mybatis.user limit #{startIndex},#{pageSize}
</select>
3、测试
@Test
public void getUserBylimit(){
SqlSession sqlsession = MybatisUtils.getSqlsession();
UserMapper mapper = sqlsession.getMapper(UserMapper.class);
HashMap<String, Integer> map = new HashMap<String, Integer>();
map.put("startIndex",0);
map.put("pageSize",2);
List<User> userList = mapper.getUserByLimit(map);
for (User user : userList) {
System.out.println(user);
}
sqlsession.close();
}
8、使用注解开发
8.1、面向接口编程
-
大家之前都学过面向对象编程,也学习过接口,但在真正的开发中,很多时候我们会选择面向接口编程
-
根本原因:解耦,可拓展,提高复用,分层开发中,上层不用管具体的实现,大家都遵守共同的标准,使得开发变得更容易,规范性更好
-
在一个面向对象的系统中,系统的各种功能是由许许多多的不同对象协作完成的。在这种情况下,各个对象内部是如何实现自己的,对系统设计人员来讲就不那么重要了;
-
而各个对象之前的协作关系则成为系统设计的关键,小到不同类之间的通信,大到各模块之间的交互,在系统设计之初都是要着重考虑的,这也是系统设计的主要工作内容,面向接口编程就是指按照这种思想来编程。关于接口的理解
-
接口从更深层次的理解,应是定义(规范,约束)与实现(名实分离)的分离。
-
接口的本身反映了系统设计人员对系统的抽象理解。
-
接口应有两类:
- 第一类是对一个个体的抽象,它可对应为一个抽象体(abstract class);
- 第二类是对一个个体某一方面的抽象,即形成一个抽象面(interface);
-
一个体有可能有多个抽象面,抽象体与抽象面是有区别的
三个面向区别
- 面向对象是指,我们考虑问题时,以对象为单位,考虑它的属性及方法
- 面向过程是指,我们考虑问题时,以一个具体的流程(事务过程)为单位,考虑它的实现。
- 接口设计与非接口设计是针对复用技术而言的,与面向对象(过程)不是一个问题,更多的体现就是对系统整体的架构。
8.2、使用注解开发
1、注解在接口上实现
@Select("select * from user")
List<User> getUser();
2、需要在核心配置文件中绑定接口
<!--绑定接口-->
<mappers>
<mapper class="com.kuang.dao.UserMapper"/>
</mappers>
3、测试使用
@Test
public void test(){
SqlSession sqlsession = MybatisUtils.getSqlsession();
UserMapper mapper = sqlsession.getMapper(UserMapper.class);
List<User> users = mapper.getUser();
for (User user : users) {
System.out.println(user);
}
sqlsession.close();
}
本质 : 反射机制实现
底层:动态代理!
Mybatis详细的执行流程!
加载 XML 配置文件:MyBatis 通过 XMLConfigBuilder 解析 mybatis-config.xml 配置文件,并创建 Configuration 对象,该对象包含了 MyBatis 执行所需的所有环境信息。
1、创建 SqlSessionFactory 对象:SqlSessionFactory 是一个接口,它是 MyBatis 的关键对象,用于创建 SqlSession 对象。在 MyBatis 中存在多种实现方式,其中常用的是 DefaultSqlSessionFactory。
2、获取 SqlSession 对象:SqlSession 是 MyBatis 的核心对象,用于执行 SQL 语句、提交或回滚事务等操作。开发者可以通过 SqlSessionFactory 工厂方法 openSession() 获取 SqlSession 实例。
3、创建 Executor 对象:每个 SqlSession 在创建时都会创建一个对应的 Executor 对象,在 MyBatis 中存在多种 Executor 实现方式,其中常用的是 SimpleExecutor。
4、创建 MappedStatement 对象:MappedStatement 对象包含了一条 SQL 语句的相关信息,如 SQL 语句、参数类型、返回类型等信息。MyBatis 会将所有的 SQL 语句都封装成一个个 MappedStatement 对象。
5、执行 SQL 语句:在执行 SQL 语句之前,MyBatis 会先通过 ParameterHandler 处理 SQL 语句中的参数,然后再通过 StatementHandler 执行 SQL 语句。最后,MyBatis 会通过 ResultHandler 将结果集映射为 Java 对象并返回。
6、提交事务:如果开发者在执行完 SQL 语句之后调用了 SqlSession 的 commit() 方法,则会提交事务;否则,会回滚事务。
总之,MyBatis 的执行流程可以分为加载 XML 配置文件、创建 SqlSessionFactory 对象、获取 SqlSession 对象、创建 Executor 对象、创建 MappedStatement 对象、执行 SQL 语句和提交事务等几个步骤,这些步骤依次串联起来,完成了对数据库的访问和操作。
8.3、CRUD
1、我们可以在工具类创建的时候实现自动提交事务!
public static SqlSession getSqlsession() {
// SqlSession sqlSession = sqlSessionFactory.openSession();
// return sqlSession;
// 前两行代码优化后
return sqlSessionFactory.openSession(true);
}
2、编写接口,增加注解
public interface UserMapper {
@Select("select * from user")
List<User> getUser();
//方法存在多个参数,所有的参数前面必须加上 @Param("id")注解
@Select("select * 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 = #{id}")
int deleteUser(@Param("id") int id);
}
3、测试类
@Test
public void test(){
SqlSession sqlsession = MybatisUtils.getSqlsession();
UserMapper mapper = sqlsession.getMapper(UserMapper.class);
//查询
List<User> users = mapper.getUser();
for (User user : users) {
System.out.println(user);
}
/*
//查询
User userByID = mapper.getUserByID(1);
System.out.println(userByID);
//增加
mapper.addUser(new User(8,"松松","123456"));
//改变
mapper.updateUser(new User(2,"笨蛋","321654"));
//删除
mapper.deleteUser(7);
*/
sqlsession.close();
}
注意点:一定要绑定mapper接口
每多一个接口就要绑定一次
关于@Param()注解
。基本类型的参数或String类型,需要加上
。引用类型不需要加
。如果只有一个基本类型的话,可以忽略,但是建议大家都加上!
。我们在SQL中引用的就是我们这里的@Param中设定的属性名!
#{ } 、 ${ }区别
在 MyBatis 中,#{ } 和 ${ } 都是用于参数绑定的占位符。它们的主要区别在于解析方式不同,具体如下:
1、#{ }:表示一个占位符,MyBatis 在处理时会将其替换为一个问号 ? 并通过 PreparedStatement 对象进行参数绑定。也就是说,#{ }可以有效地防止 SQL 注入攻击,并且在使用时会自动将传入的参数安全地转义,因此在实际开发中应尽量使用 #{}。
2、${ }:表示一个变量,MyBatis在处理时会直接将其替换成变量的值,并将SQL语句发送到数据库服务器执行。也就是说,{ }是一种简单粗暴的字符串替换方式,存在着 SQL 注入攻击的风险,因此在使用时应注意对参数进行必要的转义或过滤。
总之,#{ }和 ${ } 都是 MyBatis 用于参数绑定的占位符,但二者的解析方式存在差异,#{ }会被替换为一个问号 ? 并通过 PreparedStatement 对象进行参数绑定,而 ${ } 则会被直接替换成变量的值。在实际开发中,应根据需要合理使用 #{} 和 ${ },以确保程序的安全和性能。
9、Lombok
java libaary
plugs
build tools
with one annotation your class
使用步骤:
1、在IDEA中安装Lombok插件!
2、在项目中导入Lombok jar包!
<!-- https://mvnrepository.com/artifact/org.projectlombok/lombok -->
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.18.10</version>
<scope>provided</scope>
</dependency>
3、在实体类上加注解即可!
@Data
@AllArgsConstructor
@NoArgsConstructor
4、
@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
lombok常用注解说明:
博客链接:https://blog.csdn.net/weixin_43982125/article/details/126701368?ops_request_misc=&request_id=&biz_id=102&utm_term=lombok%E5%B8%B8%E7%94%A8%E6%B3%A8%E8%A7%A3&utm_medium=distribute.pc_search_result.none-task-blog-2allsobaiduweb~default-1-126701368.142v86insert_down28,239v2insert_chatgpt&spm=1018.2226.3001.4187
10、多对一
(mybatis-study06)
多个学生,对应一个老师
对于学生而言,关联, 多个学生,关联一个老师【多对一】
对于老师而言,集合, 一个老师,有很多学生【一对多】
CREATE TABLE `teacher` (
`id` INT(10) NOT NULL,
`name` VARCHAR(30) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=INNODB DEFAULT 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=INNODB DEFAULT 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');
测试环境搭建
1、导入lombok插件
2、新建实体类 Teacher、Student
@Data
public class Teacher {
private int id;
private String name;
}
@Data
public class Student {
private int id;
private String name;
//学生需要关联一个老师
private Teacher teacher;
}
3、建立Mapper接口
public interface StudentMapper {
}
public interface TeacherMapper {
}
4、建立Mapper.xml文件
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"https://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.kuang.dao.TeacherMapper">
</mapper>
5、在核心配置文件中绑定注册我们的Mapper接口或者文件!
<!--绑定接口-->
<mappers>
<mapper class="com.kuang.dao.TeacherMapper"/>
<mapper class="com.kuang.dao.StudentMapper"/>
</mappers>
6、测试查询是否成功
public class MyTest {
public static void main(String[] args) {
SqlSession sqlsession = MybatisUtils.getSqlsession();
TeacherMapper mapper = sqlsession.getMapper(TeacherMapper.class);
Teacher teacher = mapper.getTeacher(1);
System.out.println(teacher);
sqlsession.close();
}
}
1、按照查询嵌套处理(子查询)
<!--
思路:
1.查询所有的学生信息
2.根据查询出来的学生的tid,寻找对应的老师! 子查询
-->
<select id="getStudent" resultMap="StudentTeacher">
select * from student;
</select>
<resultMap id="StudentTeacher" type="Student">
<id property="id" column="id"/>
<id property="name" column="name"/>
<!--复杂的属性,我们需要单独处理。 对象:association、集合:collection -->
<association property="teacher" column="tid" javaType="Teacher" select="getTeacher"/>
</resultMap>
<select id="getTeacher" resultType="Teacher">
select * from Teacher where id = #{id}
</select>
2、按照结果嵌套处理(连表查询)
<!--按照结果嵌套处理-->
<select id="getStudent2" resultMap="StudentTeacher2">
select s.id sid,s.name sname,t.name tname
from student s,teacher t
where 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"/>
</association>
</resultMap>
回顾Mysql多对一查询方式:
。子查询
。 连表查询
11、一对多
(mybatis-student07)
比如:一个老师拥有多个学生!
对于这个老师而言,就是一对多的关系
1、环境搭建,和刚才一样
实体类
@Data
public class Student {
private int id;
private String name;
private int tid;
}
@Data
public class Teacher {
private int id;
private String name;
//一个老师拥有多个学生
private List<Student> students;
}
按照结果嵌套处理(联表查询)
<!--按结果嵌套查询-->
<select id="getTeacher" resultMap="TeacherStudent">
select s.id sid,s.name sname ,t.name tname, t.id tid
from student s ,teacher t
where s.tid = t.id and t.id = #{tid}
</select>
<resultMap id="TeacherStudent" type="Teacher">
<result property="id" column="tid"/>
<result property="name" column="tname"/>
<!--复杂的属性,我们需要单独处理。 对象:association、集合:collection
javaType="" 指定的属性类型!
集合中的泛型信息,我们使用ofType获取
-->
<collection property="students" ofType="Student">
<result property="id" column="sid"/>
<result property="name" column="sname"/>
<result property="tid" column="tid"/>
</collection>
</resultMap>
按照查询嵌套处理(子查询)
<!--子查询-->
<select id="getTeacher2" resultMap="TeacherStudent2">
select * from mybatis.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 mybatis.student where tid = #{tid}
</select>
小结
1、关联- association 【多对一】
2、集合- collection 【一对多】
3、javaType & ofType
javaType用来指定实体类中属性的类型
ofType用来指定映射到 List 或者集合中的pojo类型,泛型中的约束类型!
注意点:
。保证SQL的可读性,尽量保证通俗易懂
。注意一对多和多对一中,属性名和字段的问题!
。如果问题不好排查,可以使用日志,log4j
慢SQL 1s 1000s
面试高频
。Mysql引擎
MySQL 支持多种存储引擎,不同的存储引擎和数据库产品或系统有不同的实现。在创建表时,可以选择不同的存储引擎来对数据进行处理和管理。
以下是 MySQL 中常见的存储引擎:
1、MyISAM:这是 MySQL 5.5 以前版本中默认的存储引擎,它使用表级锁定,适合于读密集型应用,但是写操作较少的情况。它不支持事务和外键约束。
2、InnoDB:自 MySQL 5.5 开始成为默认的存储引擎,支持行级锁定、事务、外键等功能,适合于 OLTP(联机事务处理) 和高并发的应用程序。InnoDB 存储引擎使用了缓存和预读来优化性能。
3、Memory:该存储引擎将数据存储在内存中,速度非常快,但是如果出现数据库断电或服务器重启,数据会全部丢失。
4、Archive:该存储引擎为非常压缩的只追加表提供了优化。它非常适合于历史记录和日志数据的存储。
5、NDB Cluster:该存储引擎是 MySQL 集群的核心组件,拥有高可用性和高伸缩性,支持分布式数据存储。
在选择合适的存储引擎时需要考虑应用程序的特性和需求,例如是否需要支持事务,读写的比例等。
。InnoDB底层原理
InnoDB 是 MySQL 默认的事务型存储引擎,具有高可靠性、高性能、高并发和强大的事务支持。
InnoDB 存储引擎主要基于以下几个原理实现:
1、事务:InnoDB 存储引擎支持事务,并且使用多版本并发控制(MVCC)来实现高并发的读写操作。MVCC 允许读操作与写操作同时进行,提高了系统的并发性能。
2、锁机制:InnoDB 存储引擎采用多粒度锁实现并发控制,在保证数据一致性的同时尽可能提高并发性能。例如,当执行 INSERT、UPDATE、DELETE 等操作时,会对相关表或行加锁,以防止其它事务对数据的干扰。
3、缓冲池:InnoDB 存储引擎使用缓冲池来将磁盘 I/O 操作降至最低,提高访问速度。InnoDB 将磁盘上的数据页缓存到内存中,同时也将内存中的数据页写回磁盘。缓冲池大小对性能影响很大,应根据实际情况进行调整。
4、B+ 树索引:InnoDB 存储引擎使用 B+ 树索引来实现快速查询和数据获取。与其它类型的索引相比,B+ 树索引具有结构简单、空间利用率高、插入删除效率高等优点,因此在 InnoDB 存储引擎中被广泛应用。
5、日志系统:InnoDB 存储引擎使用日志系统来保证事务的原子性和持久性。当执行 INSERT、UPDATE、DELETE 等操作时,会将修改前的数据备份到 redo log 中,以便进行事务回滚或恢复操作。同时,还会记录 bin log,用于数据库的主从同步。
总之,InnoDB 存储引擎通过采用多种技术手段,实现了对大量数据的高效管理,为大型 OLTP(联机事务处理) 应用程序提供了强大的支持。
。索引及其索引优化
索引是用于快速查找数据库表中数据的一种数据结构,类似于书籍的目录。在 MySQL 中,索引是根据一个或多个字段创建的,可以提高查询速度,并且可以帮助避免全表扫描。MySQL 中常见的索引类型有以下几种:
1、B-Tree 索引:是 MySQL 最常用的索引类型,使用 B-Tree 数据结构来实现快速查找。B-Tree 索引适用于等值查找和区间查找,但对于模糊匹配的查询效果不佳。
2、哈希索引:基于哈希表实现,适用于只能进行精确匹配的查询,例如等值查找和 IN 查找。但是哈希索引不支持排序、范围查询和模糊查询。
3、全文索引:用于全文搜索的索引,支持模糊和通配符查询,适用于处理文本数据。
针对索引优化,我们可以从以下几个方面入手:
1、优化查询语句:尽量避免使用 SELECT * 语句查询全部数据,只查询需要的字段;尽量使用 WHERE 子句限制查询数据范围,以便减少扫描行数;减少复杂的 JOIN 查询,使用 EXISTS 或 IN 替代。
2、创建合适的索引:在需要快速查询的列上创建索引,但不要过度索引;使用前缀索引来优化长字符串的性能;在多个列组合时使用联合索引或者覆盖索引;考虑使用全文索引或者空间索引。
3、维护好索引:及时删除不必要的索引,定期重新组织表以减少碎片;避免使用 MySQL 执行计划中没有使用索引。
综上所述,合理的索引设计和优化是 MySQL 数据库性能优化的重点之一,可以大大提高查询效率和响应时间。
12、动态SQL
什么是动态SQL:动态SQL就是指根据不同条件生成不同的SQL语句
所谓的动态SQL,本质上还是SQL语句,只是我们可以在SQL层面,去执行一个逻辑代码。
动态SQL元素和 JSTL 或任何基于类 XML 语言的文本处理器相似,你对动,MyBatis 3 替换了之前的大部分元素,大大精简了元素种类,现在要学习的元素种类比原来的一半还要少。
if
choose (when, otherwise)
trim (where, set)
foreach
我们之前写的 SQL 语句都比较简单,如果有比较复杂的业务,我们需要写复杂的 SQL 语句,往往需要拼接,而拼接 SQL ,稍微不注意,由于引号,空格等缺失可能都会导致错误。
那么怎么去解决这个问题呢?这就要使用 mybatis 动态SQL,通过 if, choose, when, otherwise, trim, where, set, foreach等标签,可组合成非常灵活的SQL语句,从而在提高 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
创建一个基础工程
1、导包
<dependencies>
<!--mysql驱动-->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.26</version>
</dependency>
<!--mybatis-->
<!-- https://mvnrepository.com/artifact/org.mybatis/mybatis -->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.5.9</version>
</dependency>
<!--junit-->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.projectlombok/lombok -->
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.18.10</version>
<scope>provided</scope>
</dependency>
</dependencies>
<!--在build中配置resources,来防止我们的资源导出失败的问题-->
<build>
<resources>
<!-- 设置正常情况的resources目录下的properties文件-->
<resource>
<!-- 配置路径-->
<directory>src/main/resources</directory>
<includes>
<!-- 包含什么文件-->
<include>**/*.properties</include>
<include>**/*.xml</include>
</includes>
<filtering>true</filtering>
</resource>
<!-- 设置java路径的properties文件-->
<resource>
<directory>src/main/java</directory>
<includes>
<include>**/*.properties</include>
<include>**/*.xml</include>
</includes>
<filtering>true</filtering>
</resource>
</resources>
</build>
</project>
2、IDutil工具类
public class IDUtil {
public static String genId(){
return UUID.randomUUID().toString().replaceAll("-","");
}
}
3、MybatisUtils工具类
package com.kuang.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 {
private static SqlSessionFactory sqlSessionFactory;
static {
try {
//使用Mybatis第一步:获取SqlSessionFactory对象
String resource = "mybatis-config.xml";
InputStream inputStream = Resources.getResourceAsStream(resource);
sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
} catch (IOException e) {
e.printStackTrace();
}
}
//既然有了 SqlSessionFactory,顾名思义,我们可以从中获得 SqlSession 的实例。
// SqlSession 提供了在数据库执行 SQL 命令所需的所有方法。
public static SqlSession getSqlsession() {
// SqlSession sqlSession = sqlSessionFactory.openSession();
// return sqlSession;
// 前两行代码优化后
return sqlSessionFactory.openSession(true);
}
}
4、编写配置文件
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration
PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"https://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
<!--引入外部配置文件-->
<properties resource="db.properties"/>
<!--<typeAlias type="com.kuang.pojo.User" alias="User"/>-->
<settings>
<!--标准的日志工厂-->
<setting name="logImpl" value="STDOUT_LOGGING"/>
<!--是否开启驼峰命名自动映射:(解决从经典数据库列名 create_time 映射到经典 Java 属性名 createTime)-->
<setting name="mapUnderscoreToCamelCase" value="true"/>
</settings>
<!--可以额给实体类起别名-->
<typeAliases>
<package name="com.kuang.pojo"/>
</typeAliases>
<environments default="development">
<environment id="development">
<transactionManager type="JDBC"/>
<!--<dataSource type="POOLED">
<property name="driver" value="${driver}"/>
<property name="url" value="${url}"/>
<property name="username" value="${username}"/>
<property name="password" value="${password}"/>
</dataSource>-->
<dataSource type="POOLED">
<property name="driver" value="com.mysql.cj.jdbc.Driver"/>
<property name="url" value="jdbc:mysql://localhost:3306/mybatis?useSSL=false&serverTimezone=UTC&characterEncoding=utf8"/>
<property name="username" value="root"/>
<property name="password" value="123456"/>
</dataSource>
</environment>
</environments>
<!--绑定接口-->
<mappers>
<mapper class="com.kuang.dao.BlogMapper"/>
</mappers>
</configuration>
5、编写实体类
@Data
public class Blog {
private int id;
private String title;
private String author;
private Date createTime;
private int views;
}
6、编写实体类对应Mapper接口和 Mapper.xml
package com.kuang.dao;
import com.kuang.pojo.Blog;
import java.util.List;
import java.util.Map;
public interface BlogMapper {
//插入数据
int addBlog(Blog blog);
//查询博客
List<Blog> queryBlogIF(Map map);
}
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"https://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.kuang.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.blog where 1=1
<if test="title != null">
and title = #{title}
</if>
<if test="author != null">
and author = #{author}
</if>
</select>
</mapper>
7、初始化博客方法
@Test
public void addInitBlog(){
SqlSession session = MybatisUtils.getSession();
BlogMapper mapper = session.getMapper(BlogMapper.class);
Blog blog = new Blog();
blog.setId(IDUtil.genId());
blog.setTitle("Mybatis如此简单");
blog.setAuthor("狂神说");
blog.setCreateTime(new Date());
blog.setViews(9999);
mapper.addBlog(blog);
blog.setId(IDUtil.genId());
blog.setTitle("Java如此简单");
mapper.addBlog(blog);
blog.setId(IDUtil.genId());
blog.setTitle("Spring如此简单");
mapper.addBlog(blog);
blog.setId(IDUtil.genId());
blog.setTitle("微服务如此简单");
mapper.addBlog(blog);
session.close();
}
初始化数据完毕!
2、if 语句
需求:根据作者名字和博客名字来查询博客!如果作者名字为空,那么只根据博客名字查询,反之,则根据作者名来查询
1、编写接口类
List<Blog> queryBlogIf(Map map);
2、编写SQL语句
<!--需求1:
根据作者名字和博客名字来查询博客!
如果作者名字为空,那么只根据博客名字查询,反之,则根据作者名来查询
select * from blog where title = #{title} and author = #{author}
-->
<select id="queryBlogIf" parameterType="map" resultType="blog">
select * from blog where
<if test="title != null">
title = #{title}
</if>
<if test="author != null">
and author = #{author}
</if>
</select>
3、测试
@Test
public void testQueryBlogIf(){
SqlSession session = MybatisUtils.getSession();
BlogMapper mapper = session.getMapper(BlogMapper.class);
HashMap<String, String> map = new HashMap<String, String>();
map.put("title","Mybatis如此简单");
map.put("author","狂神说");
List<Blog> blogs = mapper.queryBlogIf(map);
System.out.println(blogs);
session.close();
}
这样写我们可以看到,如果 author 等于 null,那么查询语句为 select * from user where title=#{title}。
但是如果title为空呢?
那么查询语句为 select * from user where and author=#{author},这是错误的 SQL 语句,如何解决呢?请看下面的 where 语句
2、Where
修改上面的SQL语句;
<select id="queryBlogIf" parameterType="map" resultType="blog">
select * from blog
<where>
<if test="title != null">
title = #{title}
</if>
<if test="author != null">
and author = #{author}
</if>
</where>
</select>
这个“where”标签会知道如果它包含的标签中有返回值的话,它就插入一个‘where’。此外,如果标签返回的内容是以AND 或OR 开头的,则它会剔除掉。
3、Set
同理,上面的对于查询 SQL 语句包含 where 关键字,如果在进行更新操作的时候,含有 set 关键词,我们怎么处理呢?
1、编写接口方法
int updateBlog(Map map);
2、sql配置文件
<!--注意set是用的逗号隔开-->
<update id="updateBlog" parameterType="map">
update blog
<set>
<if test="title != null">
title = #{title},
</if>
<if test="author != null">
author = #{author}
</if>
</set>
where id = #{id};
</update>
3、测试
@Test
public void testUpdateBlog(){
SqlSession session = MybatisUtils.getSession();
BlogMapper mapper = session.getMapper(BlogMapper.class);
HashMap<String, String> map = new HashMap<String, String>();
map.put("title","动态SQL");
map.put("author","秦疆");
map.put("id","9d6a763f5e1347cebda43e2a32687a77");
mapper.updateBlog(map);
session.close();
}
4、choose语句
有时候,我们不想用到所有的查询条件,只想选择其中的一个,查询条件有一个满足即可,使用 choose 标签可以解决此类问题,类似于 Java 的 switch 语句
1、编写接口方法
List<Blog> queryBlogChoose(Map map);
2、sql配置文件
<select id="queryBlogChoose" parameterType="map" resultType="blog">
select * from 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>
3、测试类
@Test
public void testQueryBlogChoose(){
SqlSession session = MybatisUtils.getSession();
BlogMapper mapper = session.getMapper(BlogMapper.class);
HashMap<String, Object> map = new HashMap<String, Object>();
map.put("title","Java如此简单");
map.put("author","狂神说");
map.put("views",9999);
List<Blog> blogs = mapper.queryBlogChoose(map);
System.out.println(blogs);
session.close();
}
5、SQL片段
有时候可能某个 sql 语句我们用的特别多,为了增加代码的重用性,简化代码,我们需要将这些代码抽取出来,然后使用时直接调用。
提取SQL片段:
<sql id="if-title-author">
<if test="title != null">
title = #{title}
</if>
<if test="author != null">
and author = #{author}
</if>
</sql>
引用SQL片段:
<select id="queryBlogIf" parameterType="map" resultType="blog">
select * from blog
<where>
<!-- 引用 sql 片段,如果refid 指定的不在本文件中,那么需要在前面加上 namespace -->
<include refid="if-title-author"></include>
<!-- 在这里还可以引用其他的 sql 片段 -->
</where>
</select>
注意:
①、最好基于 单表来定义 sql 片段,提高片段的可重用性
②、在 sql 片段中不要包括 where
6、Foreach
将数据库中前三个数据的id修改为1,2,3;
需求:我们需要查询 blog 表中 id 分别为1,2,3的博客信息
1、编写接口
List<Blog> queryBlogForeach(Map map);
2、编写SQL语句
<select id="queryBlogForeach" parameterType="map" resultType="blog">
select * from blog
<where>
<!--
collection:指定输入对象中的集合属性
item:每次遍历生成的对象
open:开始遍历时的拼接字符串
close:结束时拼接的字符串
separator:遍历对象之间需要拼接的字符串
select * from blog where 1=1 and (id=1 or id=2 or id=3)
-->
<foreach collection="ids" item="id" open="and (" close=")" separator="or">
id=#{id}
</foreach>
</where>
</select>
3、测试
@Test
public void testQueryBlogForeach(){
SqlSession session = MybatisUtils.getSession();
BlogMapper mapper = session.getMapper(BlogMapper.class);
HashMap map = new HashMap();
List<Integer> ids = new ArrayList<Integer>();
ids.add(1);
ids.add(2);
ids.add(3);
map.put("ids",ids);
List<Blog> blogs = mapper.queryBlogForeach(map);
System.out.println(blogs);
session.close();
}
小结:其实动态 sql 语句的编写往往就是一个拼接的问题,为了保证拼接准确,我们最好首先要写原生的 sql 语句出来,然后在通过 mybatis 动态sql 对照着改,防止出错。多在实践中使用才是熟练掌握它的技巧。
动态SQL在开发中大量的使用,一定要熟练掌握!
13、缓存(未听完)
13.1、简介
13.1.1、什么是缓存【Cache】
存在内存中的临时数据
将用户经常查询的数据放在缓存(内存)中,用户去查询数据就不用了从磁盘上(关系型数据库数据文件)查询,从缓存中查询,从而提高查询效率,解决了高并发系统的性能问题
13.1.2、为什么使用缓存
?
减少和数据库的交互次数,较少系统开销,提高系统效率
13.1.3、什么样的数据能使用缓存?
经常查询而且不经常改变的数据
13.2、Mybatis缓存
MyBatis包含一个非常强大的查询缓存特性,它可以非常方便地定制和配置缓存。缓存可以极大的提升查询效率。
MyBatis系统中默认定义了两级缓存:一级缓存和二级缓存
默认情况下,只有一级缓存开启。(SqlSession级别的缓存,也称为本地缓存)
二级缓存需要手动开启和配置,他是基于namespace级别的缓存。
为了提高扩展性,MyBatis定义了缓存接口Cache。我们可以通过实现Cache接口来自定义二级缓存
13.3、一级缓存
一级缓存也叫本地缓存:
与数据库同一次会话期间查询到的数据会放在本地缓存中。
以后如果需要获取相同的数据,直接从缓存中拿,没必须再去查询数据库;
测试步骤