mybatis框架入门:
mybatis是一个持久层框架,内部封装了jdbc,我们只需要关注sqly语句本身
使用了ORM思想实现了结果集的封装;
ORM:
object Relational Mappging 对象关系映射
就是把数据库表和实体类机实体类的属性对应起来,使我们操作实体类就实现操作数据库表
三层架构:
1.表现层:用于展现数据,也就是前端,SpringMVC框架
2.业务层:处理业务需求
3.持久层:和数据交互,负责与数据交互,Mybatis框架就作用于此
解决重新导入 maven项目 包无法下载问题
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-QH81blzM-1690163183128)(http://qiniu.xiaotao.cloud/QQ截图20210916161224.png)]
镜像服务器
<?xml version="1.0" encoding="UTF-8"?>
<settings xmlns="http://maven.apache.org/SETTINGS/1.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/SETTINGS/1.0.0 http://maven.apache.org/xsd/settings-1.0.0.xsd">
<mirrors>
<mirror>
<id>nexus</id>
<name>internal nexus repository</name>
<!-- <url>http://192.168.1.100:8081/nexus/content/groups/public/</url>-->
<url>https://repo.maven.apache.org/maven2</url>
<mirrorOf>central</mirrorOf>
</mirror>
</mirrors>
</settings>
解决报红问题
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-aCwAKFsa-1690163183129)(http://qiniu.xiaotao.cloud/QQ截图20210916161718.png)]
把 pom.xml 中对应的依赖先删除,然后刷新右侧, 之后再把依赖粘贴到pom.xml中, 再次刷新右侧就好了
第一个Mybatis
创建一个maven —>配置pom.xml —>导入jar包
创建依赖:
<dependencies>
<!--mysql驱动-->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.20</version>
</dependency>
<!--mybatis-->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.5.7</version>
</dependency>
<!--junit-->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>3.8.2</version>
<scope>test</scope>
</dependency>
</dependencies>
创建一个模块:
核心配置文件
<?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-->
<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/student?useUnicode=true&characterEncoding=utf-8&useSSL=false&serverTimezone=GMT%2B8"/>
<property name="username" value="root"/>
<property name="password" value="123456"/>
</dataSource>
</environment>
</environments>
<!--每一个Mapper.xml都需要在Mybatis核心配置文件中注册-->
<mappers>
<mapper resource="com/tao/Dao/StuMapper.xml"/>
</mappers>
</configuration>
mybatis工具类:
public class MybatisUtil {
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 命令所需的所有方法。你可以通过 SqlSession 实例来直接执行已映射的 SQL 语句
// true 自动提交事务
public static SqlSession getSqlSession(){
return sqlSessionFactory.openSession(true);
}
}
实体类:
Dao接口:
public interface IStuMapper {
List<StuModel> getStudentList();
}
接口实现类:(由原来的impl转换为Mapper配置文件)
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<!--namespace 绑定一个对应的Mapper接口-->
<mapper namespace="com.tao.Dao.IStuMapper">
<!--select语句 id : 方法名-->
<select id="getStudentList" resultType="com.tao.Model.StuModel">
select * from stuInfo;
</select>
</mapper>
测试:
@Test
public void test(){
//获得SqlSession对象
SqlSession sqlSession = MybatisUtil.getSqlSession();
//执行sql 方式一:getMapper()
IStuMapper stuMapper = sqlSession.getMapper(IStuMapper.class);
List<StuModel> stuModelList = stuMapper.getStudentList();
for (StuModel stu:stuModelList) {
System.out.println(stu);
}
//关闭SqlSession
sqlSession.close();
}
注:
配置文件xml中尽量不要出现中文,若要使用把 encoding=“UTF-8” -----> encoding=“UTF8”
CRUD
namespace中的包名要和Dao/mapper接口中的包名一致
select
<select id="selAll" resultType="com.zhang.pojo.StuPojo">
select * from stuInfo;
</select>
id : namespace中的方法名。
resultType:Sql语句的返回值。
parameterType :参数类型
増删改必须提交事物
Insert
<insert id="insertStu" parameterType="com.zhang.pojo.StuPojo">
insert into stuInfo(stu_id, stu_name, stu_sex, stu_age, stu_address) values (null,#{stu_name},#{stu_sex},#{stu_age},#{stu_address});
</insert>
update
<update id="updateStu" parameterType="com.zhang.pojo.StuPojo">
update stuInfo set stu_name = #{stu_name},stu_sex = #{stu_sex},stu_age = #{stu_age},stu_address = #{stu_address} where stu_id = #{stu_id};
</update>
delete
<delete id="delStu" parameterType="com.zhang.pojo.StuPojo">
delete from stuInfo where stu_id = #{id};
</delete>
注:
标签不要匹配错
resource绑定mapper,需要使用路径。
万能Map
实体类或数据库中的表,字段或参数过多时,应该考虑用Map。
接口
int insertStuMap(Map<String,Object> map); //添加通过Map
<!--后面的字段名可以任意起,不用跟数据库一致-->
<insert id="insertStuMap" parameterType="map">
insert into stuInfo(stu_id, stu_name, stu_sex, stu_age, stu_address) values (null,#{name},#{sex},#{age},#{address});
</insert>
// 测试
@Test
public void AddStuMap(){
Map<String,Object> map = new HashMap<>();
map.put("name","xiao");
map.put("sex","女");
map.put("age",17);
map.put("address","重庆");
int row = mapper.insertStuMap(map);
if(row >= 1){
System.out.println("添加成功");
}
//提交事物
sqlSession.commit();
//关闭SqlSession
sqlSession.close();
}
Map传递参数,直接在sql中取出key即可。
对象传递参数,直接在sql中取对象即可。
只有一个基本类型参数的情况下,可以直接在sql中取到。
模糊查询
<select id="selAllLike" resultType="com.zhang.pojo.StuPojo">
select * from stuInfo where stu_name like "%"#{val}"%";
</select>
配置解析
核心配置文件
mybatis-config.xml
Mybatis配置文件包含了会深深影响Mybatis行为的设置和属性信息。
configuration(配置)
properties(属性)
settings(设置)
typeAliases(类型别名)
typeHandlers(类型处理器)
objectFactory(对象工厂)
plugins(插件)
environments(环境配置)
environment(环境变量)
transactionManager(事务管理器)
dataSource(数据源)
databaseIdProvider(数据库厂商标识)
mappers(映射器)
环境配置(environments)
MyBatis 可以配置成适应多种环境
尽管可以配置多个环境,但每个 SqlSessionFactory 实例只能选择一种环境。
Mybatis默认事物管理器是JDBC,连接池:POOLED
属性(properties)
我们可以通过properties属性来实现引用配置文件
这些属性可以在外部进行配置,并可以进行动态替换。你既可以在典型的 Java 属性文件中配置这些属性,也可以在 properties 元素的子元素中设置
编写配置文件 (jdbc.properties)
userName=root
userPwd=123456
url=jdbc:mysql://localhost:3306/student?useUnicode=true&characterEncoding=utf-8&useSSL=false&serverTimezone=GMT%2B8
dirver=com.mysql.jdbc.Driver
在核心配置文件中映射
<!--Import external configuration files-->
<properties resource="jdbc.properties"></properties>
<environments default="development">
<environment id="development">
<transactionManager type="JDBC"/>
<dataSource type="POOLED">
<property name="driver" value="${driver}"/>
<property name="url" value="${url}"/>
<property name="username" value="${userName}"/>
<property name="password" value="${userPwd}"/>
</dataSource>
</environment>
</environments>
类型别名(typeAliases)
类型别名可为 Java 类型设置一个缩写名字。 它仅用于 XML 配置,意在降低冗余的全限定类名书写
<!-- 起别名 -->
<typeAliases>
<typeAlias type="com.zhang.pojo.StuPojo" alias="StuPojo"/>
</typeAliases>
也可以指定一个包名,MyBatis 会在包名下面搜索需要的 Java Bean ,在没有注解的情况下,会使用 Bean 的首字母小写的非限定类名来作为它的别名
<!-- 起别名 -->
<typeAliases>
<typeAlias type="com.zhang.pojo" />
</typeAliases>
在实体类比较少时,使用第一种 ------- 如果实体类多的情况下,建议使用第二种
设置(settings)
MyBatis 中极为重要的调整设置,它们会改变 MyBatis 的运行时行为
映射器(mappers)
MapperRegistry:注册绑定我们的Mapper文件。
方式一:【推荐使用】
<!--每个Mapper.xml都需要在Mybatis核心配置文件中注册-->
<mappers>
<mapper resource="com/zhang/mapper/StuMapper.xml"/>
</mappers>
方式二:使用class文件绑定注册
注:
- 接口和他的Mapper配置文件必须同名
- 接口和他的Mapper配置文件必须在同一个包下
<mappers>
<mapper class="com.zhang.mapper.StuMapper"/>
</mappers>
方式二:使用扫描包绑定注册
注:
- 接口和他的Mapper配置文件必须同名
- 接口和他的Mapper配置文件必须在同一个包
<mappers>
<package name="com.zhang.mapper"/>
</mappers>
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-ZrHlSt4m-1690163183130)(C:\Users\Administrator\Desktop\QQ截图20210802190410.png)]
作用域(Scope)和生命周期
作用域和生命周期类别是至关重要的,因为错误的使用会导致非常严重的并发问题
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-YoBxm7D1-1690163183130)(C:\Users\Administrator\Desktop\QQ截图20210802192455.png)]
SqlSessionFactoryBuilder
- 一旦创建了 SqlSessionFactory,就不再需要它
- 局部变量
SqlSessionFactory
- 可以想象为:数据库连接池
- SqlSessionFactory 一旦被创建就应该在应用的运行期间一直存在,没有任何理由丢弃它或重新创建另一个实例
- 使用单例模式或者静态单例模式
SqlSession
-
连接到连接池的一个对象
-
SqlSession 的实例不是线程安全的,因此是不能被共享的,所以它的最佳的作用域是请求或方法作用域
-
返回一个响应后,就应该立即关闭它
解决属性名和字段名不一致的问题
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-xicSofKy-1690163183131)(http://qiniu.xiaotao.cloud/QQ截图20210803133251.png)]
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-jYA8DXvf-1690163183131)(http://qiniu.xiaotao.cloud/QQ截图20210803133305.png)]
方式一:
1.起别名
<select id="selAll" resultType="pojo">
select id, name as testName from test;
</select>
方式二:
2.resultMap
结果集映射
<!--id:下面的查询语句的resultMap属性 -->
<resultMap id="testMap" type="pojo">
<!--column:数据库中的字段 property:实体类中的字段-->
<result column="id" property="id"/>
<result column="name" property="testName"/>
</resultMap>
<select id="selAll" resultMap="testMap">
select * from test;
</select>
日志
日志工厂
如果一个数据库操作出现了异常,我们要排错,就需要日志。
原来:sout debug 现在:日志工厂
logImpl : 指定MyBatis所有日志的具体实现。未指定时自动查找
log4j
STDOUT_LOGGING:标准日志输出
在MyBatis中具体使用哪一个日志实现,在设置中设定
<settings>
<setting name="logImpl" value="STDOUT_LOGGING"/>
</settings>
log4j:
- 是Apache的一个开源项目,可控制日志信息输送的目的地是控制台,文件,GUI组件
- 可控制每一条日志的输出格式
- 定于每一条日志信息的级别
- 通过配置文件灵活进行配置,而不需要修改应用的代码
使用:
- 导入log4j的jar包
<!-- https://mvnrepository.com/artifact/log4j/log4j -->
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.17</version>
</dependency>
- log4j.parperties
#将等级为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/zhang.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
- 配置log4j为日志的实现
<settings>
<setting name="logImpl" value="LOG4J"/>
</settings>
简单使用:
- 在要使用log4j的类中,导入包
import org.paache.log4j.Logger
- 日志对象,参数为当前类的class
static Logger logger = Logger.getLogger(StuMapperTest.class); //StuMapperTest : 当前类的类名
- 日志级别
logger.info("info进入了");
logger.debug("....");
logger.error("....");
分页
减少数据的处理量
Limit
使用MyBatis实现分页
- 接口
List<StuPojo> getStuLimit(Map<String,Integer> map); //分页查询
- Mapper.xml
<select id="getStuLimit" parameterType="map" resultType="StuPojo">
select * from stuInfo limit #{startIndex},#{pageSize};
</select>
- 测试
private static SqlSession sqlSession = MybatisUtil.getSqlSession();//获取sqlSession对象
private static StuMapper mapper = sqlSession.getMapper(StuMapper.class);// 执行Sql
/**
* 分页查询
*/
@Test
public void selLimit(){
Map<String, Integer> map = new HashMap<>();
map.put("startIndex",0);
map.put("pageSize",2);
List<StuPojo> list = mapper.getStuLimit(map);
for (StuPojo l : list) {
System.out.println(l);
}
//关闭SqlSession
sqlSession.close();
}
RowBounds
- 接口
List<StuPojo> getStuRowBounds(); // RowBounds 分页查询
- Mapper.xml
<select id="getStuRowBounds" resultType="StuPojo">
select * from stuInfo;
</select>
- 测试
private static SqlSession sqlSession = MybatisUtil.getSqlSession();//获取sqlSession对象
/**
* RowBounds 分页查询
*/
@Test
public void selRowBounds(){
RowBounds rowBounds = new RowBounds(0,2);
//通过java代码层面实现分页
List<StuPojo> list = sqlSession.selectList("com.zhang.mapper.StuMapper.getStuRowBounds",null,rowBounds);
for (StuPojo l : list) {
System.out.println(l);
}
//关闭SqlSession
sqlSession.close();
}
注解
面向接口编程:
解耦,可拓展,提高复用,分层开发中,上层不用管具体的实现,遵守共同的标准,使得开发变得容易,规范性更好。
接口:
定于与实现的分离。
接口分为两类:
一个是个体的抽象,可对应为一个抽象体(abstract)
另一个是一个个体某一方面的抽象,即形成一个抽象面(interface)
一个个体可能有多个抽象面。
使用注解查询:
- 在接口中
@select("select * from User")
List<User> getUser();
- 绑定接口
mybatis-config.xml
<mappers>
<mapper class="com.zhang.mapper.StuMapper"/>
</mappers>
- 测试
非法存在多个参数,所有的参数必须加上 @param(“id”) 注解
@select("select * from user id = #{id}")
User getUserById(@param("id") int id);
@Insert("insert into user values(#{id},#{name},#{pwd})")
int addUser(User user);
增,删,改 在操作时需要提交事务
可在创建工具类时实现自动提交事务
public static sqlSession getSqlSession(){
return SqlSessionFactory.openSession(true);
}
关于@Param() 注解
基本类型或String 类型,需要加上
引用类型不需要加
#{} 和 &{} 区别
#{} 更加安全,能防止 sql 注入
多对一处理
多个学生,对应一个老师。
对于学生而言:关联 多个学生,关联一个老师(多对一)
对于老师而言:集合 一个老师,有很多学生(一对多)
多表联查
方式一:子查询
查询所有的学生信息,根据学生的tid,寻找对应的老师
数据
drop table if exists teacher;
create table teacher
(
id int primary key auto_increment,
name varchar(20) not null
);
drop table if exists stu;
create table stu
(
id int primary key auto_increment,
t_id int not null ,
name varchar(20) not null ,
foreign key (t_id) references teacher(id)
);
insert into teacher(id, name) VALUES (null,'t1');
insert into teacher(id, name) VALUES (null,'t2');
insert into stu(id,t_id,name) VALUES (null,1,'小灰灰');
insert into stu(id,t_id,name) VALUES (null,1,'小黑黑');
insert into stu(id,t_id,name) VALUES (null,1,'小张张');
实体类
@Data
@AllArgsConstructor
@NoArgsConstructor
public class StuModel {
private int id;
private String name;
private TeacherModel teacherModel;
}
@Data
@AllArgsConstructor
@NoArgsConstructor
public class TeacherModel {
private int id;
private String name;
}
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">
<!--Core configuration file configuration-->
<configuration>
<!-- Import external configuration files-->
<properties resource="jdbc.properties"/>
<settings>
<setting name="logImpl" value="STDOUT_LOGGING"/>
</settings>
<typeAliases>
<typeAlias type="com.zhang.pojo.StuModel" alias="student"/>
<typeAlias type="com.zhang.pojo.TeacherModel" alias="teacher"/>
</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="${userPwd}"/>
</dataSource>
</environment>
</environments>
<!--Each Mapper.xml needs to be registered in the Mybatis core configuration file-->
<mappers>
<mapper resource="com/zhang/mapper/StuMapper.xml"/>
</mappers>
</configuration>
接口
public interface StuMapper {
List<StuModel> selAll(); //查询所有
}
StuMapper.xml
<?xml version="1.0" encoding="UTF8" ?>
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<!--namespace Bind a corresponding Mapper interface-->
<mapper namespace="com.zhang.mapper.StuMapper">
<!--select resultType Entity classpath -->
<select id="selAll" resultMap="TeacherStudent" >
select * from stu;
</select>
<resultMap id="TeacherStudent" type="student">
<result property="id" column="id"/>
<result property="name" column="name"/>
<association property="teacherModel" column="t_id" javaType="teacher" select="getTeacher"/>
</resultMap>
<select id="getTeacher" resultType="teacher" >
select * from teacher where id = #{t_id};
</select>
</mapper>
test
private static SqlSession sqlSession = MybatisUtil.getSqlSession();//获取sqlSession对象
private static StuMapper mapper = sqlSession.getMapper(StuMapper.class);// 执行Sql
@Test
public void test() {
List<StuModel> ModelList = mapper.selAll();
for (StuModel s : ModelList) {
System.out.println(s);
}
//关闭SqlSession
sqlSession.close();
}
/**
StuModel(id=1, name=小灰灰, teacherModel=TeacherModel(id=1, name=t1))
StuModel(id=2, name=小黑黑, teacherModel=TeacherModel(id=1, name=t1))
StuModel(id=3, name=小张张, teacherModel=TeacherModel(id=1, name=t1))
*/
一对多处理
实体类
@Data
@AllArgsConstructor
@NoArgsConstructor
public class StuModel {
private int id;
private String name;
private int t_id;
}
@Data
@AllArgsConstructor
@NoArgsConstructor
public class TeacherModel {
private int id;
private String name;
// 一个老师拥有多个学生
private List<StuModel> students;
}
public interface StuMapper {
List<TeacherModel> getTeacher(@Param("t_id") int id); //获取指定老师下的所以学生及老师的信息
}
StuMapper.xml
<?xml version="1.0" encoding="UTF8" ?>
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<!--namespace Bind a corresponding Mapper interface-->
<mapper namespace="com.zhang.mapper.StuMapper">
<!--按结果集嵌套查询 (子查询) -->
<select id="getTeacher" resultMap="TeacherStudent">
select s.id sid,s.name sname,t.id tid,t.name tname
from stu s,teacher t
where s.t_id = t.id and t.id = #{t_id};
</select>
<resultMap id="TeacherStudent" type="teacher">
<result column="id" property="tid"/>
<result column="name" property="tname"/>
<!--
复杂的属性需要单独处理 对象:association 集合:collection
javaType: 获取 指定属性的类型 ofType:获取 集合中的泛型类型
-->
<collection property="students" ofType="student">
<result column="id" property="sid"/>
<result column="name" property="sname"/>
<result column="t_id" property="t_id"/>
</collection>
</resultMap>
</mapper>
test
private static SqlSession sqlSession = MybatisUtil.getSqlSession();//获取sqlSession对象
private static StuMapper mapper = sqlSession.getMapper(StuMapper.class);// 执行Sql
@Test
public void test() {
List<TeacherModel> list = mapper.getTeacher(1);
list.forEach(System.out::println);
//关闭SqlSession
sqlSession.close();
}
动态Sql
动态sql 及根据不同的 条件生成不同的 sql
if
choose (when, otherwise)
trim (where, set)
foreach
@Data
@AllArgsConstructor
@NoArgsConstructor
public class BlogPojo {
private String id;
private String title;
private String author;
private Date createTime; //属性名 和 字段名不一致 数据库: create_time
private int views;
}
通过 java 类插入数据
解决属性名和字段名不一致的问题
<settings>
<!--是否开启驼峰命名自动映射-->
<setting name="mapUnderscoreToCamelCase" value="true"/>
</settings>
/**
* 产生随机id
*/
public class idUtil {
public static String getId(){
return UUID.randomUUID().toString().replaceAll("-","");
}
@Test
public void test(){
System.out.println(idUtil.getId());
}
}
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<!--namespace Bind a corresponding Mapper interface-->
<mapper namespace="com.zhang.mapper.BlogMapper">
<insert id="addBolg" parameterType="blog">
insert into blog(id, title, author, create_time, views)
VALUES (#{id},#{title},#{author},#{createTime},#{views});
</insert>
</mapper>
test
public class blogTest {
private static SqlSession sqlSession = MybatisUtil.getSqlSession();//获取sqlSession对象
private static BlogMapper mapper = sqlSession.getMapper(BlogMapper.class);// 执行Sql
@Test
public void addBlog(){
BlogPojo blog = new BlogPojo();
blog.setId(idUtil.getId());
blog.setTitle("Mybatis 如此简单");
blog.setAuthor("狂神说");
blog.setCreateTime(new Date());
blog.setViews(99999);
mapper.addBolg(blog);
blog.setId(idUtil.getId());
blog.setTitle("Java 如此简单");
mapper.addBolg(blog);
blog.setId(idUtil.getId());
blog.setTitle("Spring 如此简单");
mapper.addBolg(blog);
blog.setId(idUtil.getId());
blog.setTitle("SpringBoot 如此简单");
mapper.addBolg(blog);
//增 删 改 必须提交事务
sqlSession.commit();
//关闭SqlSession
sqlSession.close();
}
}
动态sql - if
public interface BlogMapper {
//查询博客
List<BlogPojo> queryBlogIF(Map map);
}
<select id="queryBlogIF" parameterType="map" resultType="blog">
select * from blog
<!--
where 元素只会在还没有内容时才插入 “WHERE” 子句
子句的开头为 “AND” 或 “OR”,where 元素也会将它们去除
-->
<where>
<!--根据不同条件追加if-->
<if test="title != null">
title = #{title}
</if>
<if test="author != null">
and author = #{author}
</if>
</where>
</select>
@Test
public void queryBlogIF(){
HashMap map = new HashMap();
map.put("title","Mybatis 如此简单");
map.put("author","狂神说");
List<BlogPojo> list = mapper.queryBlogIF(map);
list.forEach(System.out::println);
}
// 753189cb97744b48ae7154f371ae51b3, Mybatis 如此简单, 狂神说, 2021-09-16 19:12:24, 99999
动态sql - Choose
List<BlogPojo> queryBlogChoose(Map map);
<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>
@Test
public void queryBlogChoose(){
HashMap map = new HashMap();
map.put("views",99999);
List<BlogPojo> list = mapper.queryBlogChoose(map);
list.forEach(System.out::println);
}
动态sql - set(update)
int updateBlog(Map map); //修改博客
<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>
@Test
public void updateBlog(){
HashMap map = new HashMap();
map.put("id","97f353162321432d939c332508e738c6");
map.put("author","狂神说!!!!");
mapper.updateBlog(map);
//增 删 改 必须提交事务
sqlSession.commit();
//关闭SqlSession
sqlSession.close();
}
所谓的动态SQL 本质还是SQL语句 只是我们可以在sql层面 去执行一个逻辑代码
动态sql - foreach
List<BlogPojo> queryBlogForeach(Map map);
<select id="queryBlogForeach" parameterType="map" resultType="blog">
select * from blog
<where>
<foreach collection="ids" item="id" open="and (" separator="or" close=")">
id = #{id}
</foreach>
</where>
</select>
@Test
public void queryBlogForeach(){
HashMap map = new HashMap();
ArrayList<String> list = new ArrayList<>();
list.add("bfe8561dde3040939150dab39bd91678");
list.add("ae4f2490e6f84ffd9ae1792cbf2da8ed");
map.put("ids",list);
List<BlogPojo> blogList = mapper.queryBlogForeach(map);
blogList.forEach(System.out::println);
//关闭SqlSession
sqlSession.close();
}
sql 片段
<!--将经常需要重复写的代码 封装在sql片段中 后面使用只要调用即可 不需要重复写-->
<sql id="if-title-author">
<if test="title != null">
title = #{title}
</if>
<if test="author != null">
and author = #{author}
</if>
</sql>
<select id="queryBlogIF" parameterType="map" resultType="blog">
select * from blog
<where>
<!--调用sql片段-->
<include refid="if-title-author"></include>
</where>
</select>
注:
- 最好基于单表来定义sql片段
- 不要存在where标签
动态SQL就是在拼接sql语句 我们只要保证sql的正确性 按照sql的格式 去排列组合就可以了
缓存
查询:连接数据库 耗资源
一次查询的结果 给他暂存在一个可以直接取到的地方 --> 内存 : 缓存
我们再查询相同数据的时候 直接查询缓存 就不用再查询数据库了
- 什么是缓存【Cache】
- 存在内存中的临时数据
- 将用户经常查询的数据放在缓存中 提高查询效率 解决了高并发系统的性能问题
- 为什么使用缓存
- 减少和数据库的交互次数 减少系统开销 提高系统效率
- 什么样的数据能使用缓存
- 经常查询并且不经常改变的数据
Mybatis缓存
Mybatis 包含一个非常强大的查询缓存特性 可以非常方便的定制和配置缓存 极大的提升查询效率
分类:
- 默认情况下 只有一级缓存开启 (SqlSession级别的缓存 也称本地缓存)
- 二级缓存需要手动开启和配置 是基于 namespace 级别的缓存
- 为了提高扩展性 Mybatis 定义了缓存接口 Cache 可以通过实现Cache 接口来自定义二级缓存
一级缓存
一级缓存也叫本地缓存: SqlSession
- 与数据库同一次会话期间查询到的数据会放在本地缓存中
- 以后需要获取相同的数据 直接从缓存中拿 不需要去查询数据库
步骤:
-
开启日志
-
测试在一次Session中查询两次记录
@Test
public void sel(){
stu stu = mapper.queryStuById(1);
System.out.println(stu);
stu stu1 = mapper.queryStuById(1);
System.out.println(stu1);
System.out.println(stu == stu1);
//关闭SqlSession
sqlSession.close();
}
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-xrkL7DXn-1690163183132)(http://qiniu.xiaotao.cloud/QQ截图20210918103836-1631932832491.png)]
缓存失效的情况:
-
查询不同的东西
-
增删改操作 可能会改变原来的数据 所以必定会刷新缓存
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-68HhTuBT-1690163183132)(http://qiniu.xiaotao.cloud/QQ截图20210918110702.png)]
-
查询不同的Mapper.xml
-
手动清理缓存
@Test
public void sel(){
stu stu = mapper.queryStuById(1);
System.out.println(stu);
//手动清理缓存
sqlSession.clearCache();
stu stu1 = mapper.queryStuById(1);
System.out.println(stu1);
System.out.println(stu == stu1);
//关闭SqlSession
sqlSession.close();
}
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-wzZRFN0l-1690163183132)(http://qiniu.xiaotao.cloud/QQ截图20210918112825.png)]
一级缓存默认是开启的 只在一次SqlSession中有效 也就是拿到了连接到关闭连接这个区段 一级缓存就是一个Map
二级缓存
- 二级缓存也叫全局缓存 一级缓存作用域再低了 所以需要二级缓存
- 基于 namespace 级别的缓存 一个名称空间 对应一个二级缓存
- 工作机制
- 一个会话查询一条数据 这个数据就会被放在当前会话的一级缓存中
- 如果当前会话关闭了 这个会话对应的一级缓存就没了 ,但是我们想要的是 会话关闭 一级缓存中的数据被保存到二级缓存中
- 新的会话查询信息 就可以从二级缓存中获取内容
- 不同的mapper 查询的数据会放在对应的缓存(map)中
步骤:
- 开启全局缓存
<settings>
<!--显示的开启全局缓存-->
<setting name="cacheEnabled" value="true"/>
</settings>
<?xml version="1.0" encoding="UTF8" ?>
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<!--namespace Bind a corresponding Mapper interface-->
<mapper namespace="com.zhang.mapper.stuMapper">
<!-- 开启二级缓存-->
<cache eviction="FIFO"
flushInterval="60000"
size="512"
readOnly="true"/>
<select id="queryStuById" resultType="stu" useCache="true">
select * from stu where id = #{id}
</select>
</mapper>
@Test
public void sel1(){
SqlSession sqlSession = MybatisUtil.getSqlSession();
SqlSession sqlSession1 = MybatisUtil.getSqlSession();
stuMapper mapper = sqlSession.getMapper(stuMapper.class);
stuMapper mapper1 = sqlSession1.getMapper(stuMapper.class);
stu stu = mapper.queryStuById(1);
System.out.println(stu);
sqlSession.close();
stu stu1 = mapper1.queryStuById(1);
System.out.println(stu1);
sqlSession1.close();
System.out.println(stu == stu1);
}
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-ZNjndeQm-1690163183133)(http://qiniu.xiaotao.cloud/QQ截图20210918115908.png)]
问题:我们需要将实体序列化 否则就会报错
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-KzKo3ZZi-1690163183133)(http://qiniu.xiaotao.cloud/QQ截图20210918120559.png)]
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-zzQBPEMg-1690163183133)(http://qiniu.xiaotao.cloud/QQ截图20210918120713.png)]
标识一个类的对象可以被序列化。
小结
- 只要开启了二级缓存 在同一个Mapper下就有效
- 所有的数据都会先放在一级缓存中
- 只有当会话提交 或者关闭时 才会提交到二级缓存中
自定义缓存 ehcache
Ehcache 是一种广泛使用的开源java分布式缓存 主要面向通用缓存
导入依赖
<!-- https://mvnrepository.com/artifact/org.mybatis.caches/mybatis-ehcache -->
<dependency>
<groupId>org.mybatis.caches</groupId>
<artifactId>mybatis-ehcache</artifactId>
<version>1.2.1</version>
</dependency>
<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分为内存和磁盘两级,此属性定义磁盘的缓存位
置。参数解释如下:
user.home – 用户主目录
user.dir – 用户当前工作目录
java.io.tmpdir – 默认临时文件路径
-->
<diskStore path="./tmpdir/Tmp_EhCache"/>
<defaultCache
eternal="false"
maxElementsInMemory="10000"
overflowToDisk="false"
diskPersistent="false"
timeToIdleSeconds="1800"
timeToLiveSeconds="259200"
memoryStoreEvictionPolicy="LRU"/>
<cache
name="cloud_user"
eternal="false"
maxElementsInMemory="5000"
overflowToDisk="false"
diskPersistent="false"
timeToIdleSeconds="1800"
timeToLiveSeconds="1800"
memoryStoreEvictionPolicy="LRU"/>
<!--
defaultCache:默认缓存策略,当ehcache找不到定义的缓存时,则使用这个缓存策
略。只能定义一个。
-->
<!--
name:缓存名称。
maxElementsInMemory:缓存最大数目
maxElementsOnDisk:硬盘最大缓存个数。
eternal:对象是否永久有效,一但设置了,timeout将不起作用。
overflowToDisk:是否保存到磁盘,当系统当机时
timeToIdleSeconds:设置对象在失效前的允许闲置时间(单位:秒)。仅当
eternal=false对象不是永久有效时使用,可选属性,默认值是0,也就是可闲置时间无穷大。
timeToLiveSeconds:设置对象在失效前允许存活时间(单位:秒)。最大时间介于创建
时间和失效时间之间。仅当eternal=false对象不是永久有效时使用,默认是0.,也就是对象存
活时间无穷大。
diskPersistent:是否缓存虚拟机重启期数据 Whether the disk store
persists between restarts of the Virtual Machine. The default value is
false.
diskSpoolBufferSizeMB:这个参数设置DiskStore(磁盘缓存)的缓存区大小。默
认是30MB。每个Cache都应该有自己的一个缓冲区。
diskExpiryThreadIntervalSeconds:磁盘失效线程运行时间间隔,默认是120秒。
memoryStoreEvictionPolicy:当达到maxElementsInMemory限制时,Ehcache将
会根据指定的策略去清理内存。默认策略是LRU(最近最少使用)。你可以设置为FIFO(先进先
出)或是LFU(较少使用)。
clearOnFlush:内存数量最大时是否清除。
memoryStoreEvictionPolicy:可选策略有:LRU(最近最少使用,默认策略)、
FIFO(先进先出)、LFU(最少访问次数)。
FIFO,first in first out,这个是大家最熟的,先进先出。
LFU, Less Frequently Used,就是上面例子中使用的策略,直白一点就是讲一直以
来最少被使用的。如上面所讲,缓存的元素有一个hit属性,hit值最小的将会被清出缓存。
LRU,Least Recently Used,最近最少使用的,缓存的元素有一个时间戳,当缓存容
量满了,而又需要腾出地方来缓存新的元素的时候,那么现有缓存元素中时间戳离当前时间最远的
元素将被清出缓存。
-->
</ehcache>