MyBatis
1、什么是Mybatis
1、来历
-
MyBatis 本是apache的一个开源项目iBatis,
-
2010年这个项目由 迁移到了[google code](https://baike.baidu.com/item/google code/2346604),并且改名为MyBatis 。
-
2013年迁移到Github。
-
iBATIS一词来源于“internet”和“abatis”的组合,是一个基于Java的持久层框架。
-
iBATIS提供的持久层框架包括SQL Maps和Data Access Objects(DAOs)
2、基本内容
-
MyBatis 是一款优秀的持久层框架(DAO),
-
它支持定制化 SQL、存储过程以及高级映射。
-
MyBatis 避免了几乎所有的 JDBC 代码和手动设置参数以及获取结果集。
-
MyBatis 可以使用简单的 XML 或注解来配置和映射原生信息,将接口和 Java 的 POJOs(Plain Ordinary Java Object,普通的 Java对象)映射成数据库中的记录。
3.持久化
数据持久化
-
持久化就是将程序的数据在持久状态和瞬时状态转化的过程
-
数据库(jdbc),io文件持久化
-
生活中:冷藏、罐头
为什么需要持久化?
内存太贵惹
4.持久层
Dao层,Service层,controller层。。。
- 完成持久化工作的代码块
- 层界限十分明显
5.为什么需要MyBatis
帮助程序员将数据存放到数据库中
传统的JDBC代码太复杂了—>简化——>框架
不用MyBatis也可以
优点
- 简单易学:最简单安装只要两个jar文件+配置几个sql映射文件易于学习,
- 灵活:mybatis不会对应用程序或者数据库的现有设计强加任何影响。
- sql写在xml里,便于统一管理和优化。通过sql语句可以满足操作数据库的所有需求。
- sql和代码的分离,提高了可维护性。
- 解除sql与程序代码的耦合:通过提供DAO层,将业务逻辑和数据访问逻辑分离,使系统的设计更清晰,更易维护,更易单元测试。
- 提供映射标签,支持对象与数据库的orm字段关系映射
- 提供对象关系映射标签,支持对象关系组建维护
- 提供xml标签,支持编写动态sql。
4.、如何获得Mybatis
1.从GitHub获取
因为MyBatis是开源的,所以可以从从开源的网站下载
https://github.com/mybatis/mybatis-3
![image-20210517160840339](https://gitee.com/cl2854697833/my-picture/raw/master/img/202205041716766.png)
2.Maven
https://mvnrepository.com/artifact/org.mybatis/mybatis/3.5.6
<!-- https://mvnrepository.com/artifact/org.mybatis/mybatis -->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.5.7</version>
</dependency>
3.中文文档地址:
https://mybatis.org/mybatis-3/zh/index.html
5.准备工作
环境
- JDK 1.8
- Mysql 5.7
- maven 3.6.1
- IDEA
回顾
- JDBC
- Mysql
- java基础
- Maven
- junit
SSM框架:配置文件,最好看官网文档
MyBatis中文文档
https://mybatis.org/mybatis-3/zh/index.html
2、第一个MyBatis程序(入门)
思路:
- 搭建环境(Maven)
- 导入myBatis
- 编写代码
- 测试
2.1、搭建环境
搭建数据库
CREATE DATABASE mybatis
USE mybatis
CREATE TABLE `user`(
`id` INT (10) NOT NULL PRIMARY KEY,
`name` VARCHAR (30) DEFAULT NULL,
`pwd` VARCHAR (10) DEFAULT NULL
)ENGINE =INNODB DEFAULT CHARSET=utf8;
INSERT INTO `user`(`id`,`name`,`pwd`) VALUES
(1,"cc",'123456'),
(2,"aa",'123'),
(3,"bb",'1234')
新建项目
- 新建一个普通的maven项目
![image-20210517170316512](https://gitee.com/cl2854697833/my-picture/raw/master/img/202205041716767.png)
- 删除src目录,父工程,创建子工程
-
导入依赖
- mysql
- mybatis
- junit
为什么在maven的pom.xml中导入项目依赖还是红色的!!!
把maven版本换一下
<!--导入依赖-->
<dependencies>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.11</version>
</dependency>
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.4.6</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
</dependency>
</dependencies>
<build>
<resources>
<resource>
<directory>src/main/resources</directory>
<includes>
<include>**/*.properties</include>
<include>**/*.xml</include>
</includes>
<filtering>true</filtering>
</resource>
<resource>
<directory>src/main/java</directory>
<includes>
<include>**/*.properties</include>
<include>**/*.xml</include>
</includes>
<filtering>true</filtering>
</resource>
</resources>
</build>
2.2、创建一个项目
- 编写mybatis核心配置文件mybatis-config.xml,将网页中的代码粘贴进去
从 XML 中构建 SqlSessionFactory
每个基于 MyBatis 的应用都是以一个 SqlSessionFactory 的实例为核心的。
XML 配置文件中包含了对 MyBatis 系统的核心设置,包括获取数据库连接实例的数据源(DataSource)以及决定事务作用域和控制方式的事务管理器(TransactionManager)。后面会再探讨 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.cj.jdbc.Driver"/>
<property name="url"
value="jdbc:mysql://localhost:3306/mybatis?useUnicode=true&characterEncoding=utf8&useSSL=false&serverTimezone=GMT%2B8"/>
<property name="username" value="root"/>
<property name="password" value="123"/>
</dataSource>
</environment>
</environments>
<mappers>
<mapper resource="com/kuang/dao/userMapper.xml"/>
</mappers>
</configuration>
- 配置mybatis工具类
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 {
String resource = "mybatis-config.xml";
InputStream inputStream = Resources.getResourceAsStream(resource);
sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
} catch (IOException e) {
e.printStackTrace();
}
}
public static SqlSession getSqlSession() {
SqlSession sqlSession = sqlSessionFactory.openSession();
return sqlSession;
}
}
2.3、编写代码
- 实体类 pojo
package com.kuang.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 + '\'' +
'}';
}
}
- Dao接口
不需要写UserDaoInterface,直接写UserMapper.xml
package com.kuang.dao;
import com.kuang.pojo.user;
import java.util.List;
public interface userDao {
List<user> getuserList();
}
- 接口实现类 由原来的UserDaoImpl变为UserMapper.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.kuang.dao.userDao">
<select id="getuserList" resultType="com.kuang.pojo.user">
select *
from mybatis.user;
</select>
</mapper>
2.4测试
org.apache.ibatis.binding.BindingException: Type interface com.kuang.dao.userDao is not known to the MapperRegistry.
MapperRegistry是什么?
核心配置文件中注册Mappers
- junt测试
package com.kuang.dao;
import com.kuang.pojo.user;
import com.kuang.utils.MybatisUtils;
import org.apache.ibatis.session.SqlSession;
import org.junit.Test;
import java.util.List;
public class userDaoTest {
@Test
public void test() {
SqlSession sqlSession = MybatisUtils.getSqlSession();
userDao userDao = sqlSession.getMapper(userDao.class);
List<user> usersList = userDao.getuserList();
for (user user : usersList) {
System.out.println(user);
}
sqlSession.close();
}
}
测试中可能会遇到的问题
- 配置文件没有注册!
- 绑定接口不对
- 方法名不对
- 返回类型不对
- maven导出资源问题
1.连接数据库
2.导入相关jar(mybatis,sql。。)
3.建造工具类《——编写配置文件
4.编写实体类——接口——Mapper
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-Rbgbamh8-1651656024038)(https://gitee.com/cl2854697833/my-picture/raw/master/img/202205041716774.png)]
3、CRUD
1、namespace
namespace中的包名要和Dao/Mapper接口的名字一样!!
2、select
<?xml version="1.0" encoding="GBK" ?>
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.kuang.dao.userMapper">
<select id="getuserList" resultType="com.kuang.pojo.user">
select * from mybatis.user;
</select>
</mapper>
选择、查询语句
-
id:就是对应的namespace中的方法名
-
resulType:SQL语句执行的返回值
-
parameterType:参数的类型
1.编写接口
2.配置xm文件(编写Mapper中的SQL语句)
3.test测试
3、insert
<!-- 对象中的属性可以直接取出来-->
<insert id="addUser" parameterType="com.kuang.pojo.user" >
-- 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、错误排查
7、万能Map
假设我们的实体类,或者数据库中的表字段或者参数过多,我们应当考虑Map!
//2.0万能map Map<String,Object>
int addUser2(Map<String,Object> map);
<!--测试万能map
传递map的key
-->
<insert id="addUser2" parameterType="map">
insert into mybatis.user(id, name, pwd) VALUES (#{userid},#{userName},#{PassWord})
</insert>
//2.0测试{万能Map}
@Test
public void adduser2(){
SqlSession sqlSession = MybatisUtils.getSqlSession();
userMapper mapper = sqlSession.getMapper(userMapper.class);
HashMap<String, Object> map = new HashMap<>();
map.put("userid",5);
map.put("userName","张三");
map.put("PassWord","11232");
mapper.addUser2(map);
sqlSession.commit();
sqlSession.close();
}
Mapper传递参数,在sql直接取出key即可! 【 parameterType="map“】
对象传递参数,直接在sql中去对象的属性即可!【 parameterType="object】
只有一个基本类型参数的情况下,可以直接在sql中取到
多个参数用Map,或者注解!
8、模糊查询
@Test
public void getUser(){
SqlSession sqlSession = MybatisUtils.getSqlSession();
userMapper mapper = sqlSession.getMapper(userMapper.class);
List<user> users = mapper.getuserList2("%张%");
for (user user : users) {
System.out.println(user);
}
sqlSession.close();
}
-
java代码执行时,传递通配符%%
-
List<user> users = mapper.getuserList2("%张%");
-
在sql拼接中使用通配符
# select * from mybatis.user where name LIKE ”%“#{value}”%“;
4、配置解析(进阶)
mybatis2
1、核心配置文件
- mybatis-cofig.xml
需要掌握的相关知识!
- configuration(配置)
- properties(属性)
- settings(设置)
- typeAliases(类型别名)
- typeHandlers(类型处理器)
- objectFactory(对象工厂)
- plugins(插件)
- environments(环境配置)
- environment(环境变量)
- transactionManager(事务管理器)
- dataSource(数据源)
- environment(环境变量)
- databaseIdProvider(数据库厂商标识)
- mappers(映射器)
2、环境配置
MyBatis 可以配置成适应多种环境
不过要记住:尽管可以配置多个环境,但每个 SqlSessionFactory 实例只能选择一种环境。
- 每个数据库对应一个 SqlSessionFactory 实例
事务管理器(transactionManager)
在 MyBatis 中有两种类型的事务管理器(也就是 type="[JDBC|MANAGED]"):
- JDBC – 这个配置直接使用了 JDBC 的提交和回滚设施,它依赖从数据源获得的连接来管理事务作用域。
提示 如果你正在使用 Spring + MyBatis,则没有必要配置事务管理器,因为 Spring 模块会使用自带的管理器来覆盖前面的配置
数据源(dataSource)
dataSource 元素使用标准的 JDBC 数据源接口来配置 JDBC 连接对象的资源。
有三种内建的数据源类型(也就是 type=“[UNPOOLED|POOLED|JNDI]”):
作为了解
<transactionManager type=“JDBC”》
<dataSource type=“POOLED”》
学会使用多套环境
Mybatis默认的事务管理器就是JDBC,连接池:POOLED.
3、属性(properties)
这些属性可以在外部进行配置,并可以进行动态替换。你既可以在典型的 Java 属性文件中配置这些属性,也可以在 properties 元素的子元素中设置。例如:[config.properties]
1.properties 元素引入
1.1 编写配置文件
driver=com.mysql.cj.jdbc.Driver
url=jdbc:mysql://localhost:3306/mybatis?useUnicode=true&characterEncoding=utf8&useSSL=false&serverTimezone=GMT%2B8
#name=root
password=123
1.2在核心配置文件中引入
<!-- 引入外部配置文件-->
<properties resource="db.properties">
<property name="name" value="root"/>
</properties>
- 可以直接引入外部文件
- 可以在里面增加一些属性配置
- 如果两个文件具有同一个字段,优先使用外部文件,因为最后读取作为方法参数传递的属性,并覆盖之前读取过的同名属性。
4.别名(typeAliases)
-
1.类型别名可为 Java 类型设置一个缩写名字。
-
它仅用于 XML 配置,意在降低冗余的全限定类名书写。
<typeAliases>
<typeAlias type="com.kuang.pojo.user" alias="User"/>
</typeAliases>
-
2.也可以指定一个包名,MyBatis 会在包名下面搜索需要的 Java Bean
-
会使用 Bean 的首字母小写的非限定类名来作为它的别名(比如 domain.blog.Author 的别名为 author)
<package name="com.kuang.pojo"/>
- 3.若有注解,则别名为其注解值。见下面的例子:
@Alias("aaaaa")
public class user {
private int id;
private String name;
private String pwd;
public user() {
}
<select id="getuserList" resultType="aaaaa" >
select * from mybatis.user;
</select>
如果实体类比较少,推荐使用第一种,
实体类较多,则可以使用第二种
第一种可以DIY别名,第二种不行,如果非要改则可以在实体上使用注解
5.设置(settings)
这是 MyBatis 中极为重要的调整设置,它们会改变 MyBatis 的运行时行为
6.其他配置
- typeHandlers(类型处理器)
- objectFactory(对象工厂)
- plugins(插件)
- [mybatis-spring-boot-starter]
- mybatis-puls
- 通用mapper
7.映射器(mappers)
首先,我们需要告诉 MyBatis 到哪里去找到这些语句。
在自动查找资源方面,Java 并没有提供一个很好的解决方案,所以最好的办法是直接告诉 MyBatis 到哪里去找映射文件。
你可以使用相对于类路径的资源引用,或完全限定资源定位符(包括 file:///
形式的 URL),或类名和包名等。例如:
方式一:
<mappers>
<mapper resource="com/kuang/dao/userMapper.xml"/>
</mappers>
方式二: 使用class文件绑定注册
注意点:
- 接口和它的Mapper配置文件必须同名
- 接口和它的Mapper配置文件必须在同一个包下
方式三:使用扫描包进行绑定注册
8.生命周期和作用域
不同作用域和生命周期类别是至关重要的,因为错误的使用会导致非常严重的并发问题。
SqlSessionFactoryBuilder:
- 一旦创建了 SqlSessionFactory,就不再需要它了
- 局部变量
SqlSessionFactory:
•说白了就是可以想象为:数据库连接池
• SqlSessionFactory 一旦被创建就应该在应用的运行期间一直存在,没有任何理由丢弃它或重新创建
另一个实例。
•因此 SqlSessionFactory 的最佳作用域是应用作用域。
•最简单的就是使用单例模式或者静态单例模式。
SqlSession
•连接到连接池的一个请求!
• SqlSession 的实例不是线程安全的,因此是不能被共享的,所以它的最佳的作用域是请求或方法作用
域。
•用完之后需要赶紧关闭,否则资源被占用!
这里面的每一个Mapper,都是一个具体的任务
5.解决属性名和字段名不一致的情况
mybatis3
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
userMapper.xml
<resultMap id="userMap" type="com.kuang.pojo.user">
<!--column数据库中的字段, property实体类中的属性 -->
<result column="id" property="id"></result>
<result column="name" property="name"></result>
<result column="pwd" property="password"></result>
</resultMap>
<select id="getUserById" parameterType="int" resultMap="userMap">
select id,name,pwd from mybatis.user where id =#{id}
</select>
-
resultmap 元素是 MyBatis 中最重要最强大的元素
-
ResultMap 的设计思想是,对于简单的语句根本不需要配置显式的结果映射,而对于复杂一点的语句
只需要描述它们的关系就行了。 -
ResultMap 最优秀的地方在于,虽然你已经对它相当了解了,但是根本就不需要显式地用到他们。
-
如果世界总是这么简单就好
6、日志
mybatis4
6.1、日志工厂
如果一个数据库操作出现了异常,需要排查,日志就是做好的帮手。
曾经:sout、debug
现在:日志工厂
Mybatis 通过使用内置的日志工厂提供日志功能。内置日志工厂将会把日志工作委托给下面的实现之一:
- SLF4J
- Apache Commons Logging
- Log4j 2
- Log4j 【掌握】
- JDK logging
- STDOUT LOGGING 【掌握】
- COMMONS LOGGING
- NO LOGGING
再mybaits中具体使用哪一个日志,再设置中设定!
STDOUT LOGGING ——>标准输出
<settings>
<setting name="logImpl" value="STDOUT_LOGGING"/>
</settings>
6.2、Log4j
Caused by: java.lang.ClassNotFoundException: org.apache.log4j.Priority
-
Log4j是Apache的一个开源项目,通过使用Log4j,我们可以控制日志信息输送的目的地是控制台、文件、GUI组件,甚至是套接口服务器、NT的事件记录器、UNIX Syslog守护进程等;
-
我们也可以控制每一条日志的输出格式
-
通过定义每一条日志信息的级别,我们能够更加细致地控制日志的生成过程
-
通过一个配置文件来灵活地进行配置,而不需要修改应用的代码。
1.导包log4j
<dependencies>
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.17</version>
</dependency>
</dependencies>
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/kuang.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
3.配置log4j为日志的实现
<settings>
<!-- 标准的日志工厂的实现-->
<!-- <setting name="logImpl" value="STDOUT_LOGGING"/>-->
<!-- log4j-->
<setting name="logImpl" value="LOG4J"/>
</settings>
4.log4j的使用,直接运行刚才的查询
简单使用
- 在要使用的Log4j的类中导入包: import org.apache.log4j.Logger;
- 日志对象,参数为当前类的class
static Logger logger = Logger.getLogger(userDaoTest.class);
3.日志级别
@Test
public void log4jTest(){
logger.info("info:进入了log4jTest");
logger.debug("debug:进入了log4jTest");
logger.error("error:进入了log4jTest");
}
7、分页
思考:为什么要分页?
- 减少数据的处理量
- 减轻服务器压力
7.1、使用Limit分页
语法:
select * from mybatis.user limit startIndex,pageSize;
select * from mybatis.user limit 3;#[0,3)
使用MyBatis实现分页,核心SQL
1.接口
//分页
List<user> getUserByLimit(Map<String,Integer> map);
2.Mapper.xml
<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);
Map<String,Integer> map=new HashMap<String,Integer>();
map.put("startIndex",0);
map.put("pageSize",2);
List<user> userByLimit = mapper.getUserByLimit(map);
for (user user : userByLimit) {
System.out.println(user);
}
sqlSession.close();
}
7.2、RowBounds分页
了解即可,不推荐使用
7.3、分页插件
https://pagehelper.github.io/
要用再看
8.使用注解开发
8.1、面向接口编程
大家之前都学过面向对象编程,也学习过接口,但在真正的开发中,很多时候我们会选择面向接口编程
根本原因:解耦,可拓展,提高复用,分层开发中,上层不用管具体的实现,大家都遵守共同的标准,使得开发
变得容易,规范性更好
在一个面向对象的系统中,系统的各种功能是由许许多多的不同对象协作完成的。在这种情况下,各个对象内部
是如何实现自己的,对系统设计人员来讲就不那么重要了;
而各个对象之间的协作关系则成为系统设计的关键。小到不同类之间的通信,大到各模块之间的交互,在系统设
计之初都是要着重考虑的,这也是系统设计的主要工作内容。面向接口编程就是指按照这种思想来编程。
关于接口的理解
- 接口从更深层次的理解,应是定义(规范,约束) 与实现 (名实分离的原则)的分离。
- 接口的本身反映了系统设计人员对系统的抽象理解。
- 接口应有两类:
第一类是对一个个体的抽象,它可对应为一个抽象体(abstract class);
第二类是对一个个体某一方面的抽象,即形成一个抽象面 (interface); - 一个体有可能有多个抽象面。抽象体与抽象面是有区别的。
三个面向区别
- -面向对象是指,我们考虑问题时,以对象为单位,考虑它的属性及方法
- -面向过程是指,我们考虑问题时,以一个具体的流程(事务过程)为单位,考虑它的实现
- -接口设计与非接口设计是针对复用技术而言的,与面向对象(过程)不是—个问题,更多的体现就是对系统整体的
架构
8.2、使用注解
详见mybatis05
1.注解在接口上实现
public interface userMapper {
@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> user = mapper.getUser();
for (com.kuang.pojo.user user1 : user) {
System.out.println(user1);
}
sqlSession.close();
}
本质:反射机制实现
底层:动态代理
Mybatis执行流程剖析
源码查看主要在面试之前多看,提高自身水平
8.3 CRUD
我们可以在创建工具类的时候选择自动提交事务
public static SqlSession getSqlSession() {
//(true);自动提交
SqlSession sqlSession = sqlSessionFactory.openSession(true);
return sqlSession;
}
编写接口,增加注解
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);//Parameter 'id' not found. Available parameters are [idd, param1]
@Insert("insert into user (id, name, pwd) VALUES (#{id},#{name},#{pwd})")
int addUser(user user);
//删
@Delete("delete from user where id =#{uid}")
int delete(@Param("uid") int id);
@Update("update user set name=#{name},pwd=#{pwd} where id=#{id}")
int updateUser(user user);
}
测试类
【注意!我们必须要将接口注册到我们的核心配置文件中!!】
关于@Param()注解
- 基本类型的参数或者String类型,需要在参数前面加上注解
- 引用类型不要加
- 如果只有一个基本类型的话,可以忽略,但是建议大家都加上。
- 我们在SQL中应用的就是我们在@Param()中设定的属性名
#{} ${}
#{}防止SQL注入
9、Lombok
见5
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.
a java library
plugs
build tools
with one annotation your class
使用步骤
1.在IDEA安装
2.在项目中导入jar包
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.18.20</version>
<scope>provided</scope>
</dependency>
3、在实体类上加注解
@Data
@AllArgsConstructor
@NoArgsConstructor
public class user {
private int id;
private String name;
private String pwd;
}
参数说明
@Getter and @Setter
@FieldNameConstants
@ToString
@EqualsAndHashCode
@AllArgsConstructor, @RequiredArgsConstructor and @NoArgsConstructor
@Log, @Log4j, @Log4j2, @Slf4j, @XSlf4j, @CommonsLog, @JBossLog, @Flogger, @CustomLog
@Data
@Builder
@SuperBuilder
@Singular
@Delegate
@Value
@Accessors
@Wither
@With
@SneakyThrows
@val
@var
experimental @var
@UtilityClass
Lombok config system
@Data:无参构造、get、set、tostring、hascode、equals
@NoArgsConstructor:保留无参构造方法,并自动完成有参构造方法
@AllArgsConstructor:只有有参构造方法,没有无参构造方法
10、多对一处理
mybatis06
- 多个学生,对应一个老师
- 对于学生而言,关联,多个学生,关联一个老师 【多对一】
- 对于老师而言,集合 ,一个老师,有很多学生 【一对多】
SQL:
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.写好数据库
3.新建实体类Teacher、Student
4.新建Mapper接口
5.编写Mapper.xml文件
6.在核心配置文件中注册我们的Mapper接口或者文件!!!【方式很多具体见4.8】
7.测试查询是否成功
按照查询嵌套处理
<!--
思路:
1.查询所有的学生信息
2.根据查询出来的学生的tid,寻找对应的老师
-->
<select id="getStudent" resultMap="StudentTeaher">
select * from student
</select>
<resultMap id="StudentTeaher" type="Student">
<result property="id" column="id"/>
<result property="name" column="name"/>
<!--复杂属性,我们需要单独处理
association:对象
集合:collection
javaType:把sql语句查询出的结果集,封装给某个类的对象(可以省略)
property:注入给实体类的某个属性
select;执行的下一个sql语句
-->
<association property="teacher" column="tid" javaType="Teacher" select="getTeacher"/>
</resultMap>
<select id="getTeacher" resultType="Teacher">
select * from teacher where id=#{id}
</select>
按照结果嵌套处理
<!-- 方法二:按照结果嵌套处理-->
<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、一对多
比如一个老师拥有多个学生
1.搭建环境
实体类
学生
package com.kuang.pojo;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
@NoArgsConstructor
@AllArgsConstructor
@Data
public class Student {
private int id;
private String name;
private int tid;
}
老师
package com.kuang.pojo;
import jdk.internal.dynalink.linker.LinkerServices;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import java.util.List;
@Data
@AllArgsConstructor
@NoArgsConstructor
public class Teacher {
private int id;
private String name;
//一个老师拥有多个学生
private List<Student> 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;
}
按照结果嵌套处理
<!-- 按结果查询-->
<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 student where tid=#{tid}
</select>
小结
1.关联 -association 【多对一】
2.集合 -collection 【一对多】
3.JavaType & ofType
1.JavaType用来指定实体类中属性的类型
2.ofType用来指定映射到List或者集合中的Pojo类型,泛型中的约束类型!
注意点:
- 保证SQL的可读性,尽量通俗易懂
- 注意一对多,多对一,属性和字段的问题
- 如果问题不好排查,可以用日志,建议使用Log4j
12、动态SQL
什么是动态SQL:动态SQL就是根据不同条件生成不同的SQL语句
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-79tWg5kR-1651656024045)(https://gitee.com/cl2854697833/my-picture/raw/master/img/202205041716793.png)]
如果你之前用过 JSTL 或任何基于类 XML 语言的文本处理器,你对动态 SQL 元素可能会感觉似曾相识。在 MyBatis 之前的版本中,需要花时间了解大量的元素。借助功能强大的基于 OGNL 的表达式,MyBatis 3 替换了之前的大部分元素,大大精简了元素种类,现在要学习的元素种类比原来的一半还要少。
- if
- choose (when, otherwise)
- trim (where, set)
- foreach
环境搭建
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;
- 导包
- 配置文件
- 编写实体类
@Data
public class Blog {
private String id;
private String title;
private String author;
private Date createTime;
private int views;
}
- 编写实体类对应的Mapper接口和Mapper.xml文件
IF
<select id="queryBlogIF" resultType="blog" parameterType="map" >
select * from mybatis.blog where 1=1
<if test="title!=null">
and title=#{title}
</if>
<if test="author!=null">
and author=#{author}
</if>
</select>
choose (when, otherwise)
<select id="queryBlogChoose" parameterType="map" resultType="blog">
select * from mybatis.blog
<where>
<choose>
<when test="title!=null">
title=#{title}
</when>
<when test="author!=null">
author=#{author}
</when>
<otherwise>
views=#{views}
</otherwise>
</choose>
</where>
public void testAddBlogIF(){
SqlSession sqlSession = MybatisUtils.getSqlSession();
BlogMapper mapper = sqlSession.getMapper(BlogMapper.class);
HashMap hashMap = new HashMap();
// hashMap.put("title","Mybatis如此简单");
hashMap.put("author","狂神说");
hashMap.put("views",9999);
// List<Blog> blogs = mapper.queryBlogIF(hashMap);
List<Blog> blogs = mapper.queryBlogChoose(hashMap);
// 使用choose时,他只要满足第一个就ok了,后面的就不管了
for (Blog blog : blogs) {
System.out.println(blog);
}
}
trim (where, set)
<select id="queryBlogIF" resultType="blog" parameterType="map" >
select * from mybatis.blog
<where>
<if test="title!=null">
title=#{title}
</if>
<if test="author!=null">
and author=#{author}
</if>
</where>
</select>
set
<update id="updateBlog" parameterType="map">
update mybatis.blog
<set>
<if test="title!=null">
title=#{title},
</if>
<if test="author!=null">
author=#{author}
</if>
where id=#{id}
</set>
</update>
@Test
public void testAddBlogIF(){
SqlSession sqlSession = MybatisUtils.getSqlSession();
BlogMapper mapper = sqlSession.getMapper(BlogMapper.class);
HashMap hashMap = new HashMap();
// hashMap.put("title","Mybatis如此简单22");
hashMap.put("author","狂2神说");
// hashMap.put("views",9999);
hashMap.put("id","0761bf777a004ee7ad1607a178ccbc8a");
/** List<Blog> blogs = mapper.queryBlogIF(hashMap);
List<Blog> blogs = mapper.queryBlogChoose(hashMap);
使用choose时,他只要满足第一个就ok了,后面的就不管了
*/
int i = mapper.updateBlog(hashMap);
}
ForEach
foreach
动态 SQL 的另一个常见使用场景是对集合进行遍历(尤其是在构建 IN 条件语句的时候)。比如:
<select id="selectPostIn" resultType="domain.blog.Post">
SELECT *
FROM POST P
WHERE ID in
<foreach item="item" index="index" collection="list"
open="(" separator="," close=")">
#{item}
</foreach>
</select>
foreach 元素的功能非常强大,它允许你指定一个集合,声明可以在元素体内使用的集合项(item)和索引(index)变量。它也允许你指定开头与结尾的字符串以及集合项迭代之间的分隔符。这个元素也不会错误地添加多余的分隔符,看它多智能!
提示 你可以将任何可迭代对象(如 List、Set 等)、Map 对象或者数组对象作为集合参数传递给 foreach。当使用可迭代对象或者数组时,index 是当前迭代的序号,item 的值是本次迭代获取到的元素。当使用 Map 对象(或者 Map.Entry 对象的集合)时,index 是键,item 是值。
至此,我们已经完成了与 XML 配置及映射文件相关的讨论。下一章将详细探讨 Java API,以便你能充分利用已经创建的映射配置。
SQL片段
有的时候,我们可能会将一些功能的部分抽取出来,方便复用!
- 使用SQL标签抽取公共的部分
- 在需要使用的地方使用Include标签引用即可
<!-- sql片段-->
<sql id="queryBlogIFSQL">
<if test="title!=null">
title=#{title}
</if>
<if test="author!=null">
and author=#{author}
</if>
</sql>
<select id="queryBlogIF" resultType="blog" parameterType="map" >
select * from mybatis.blog
<where>
<include refid="queryBlogIFSQL"></include>
</where>
</select>
- 最好基于单表来定义SQL片段
- 不要存在where标签
所谓动态SQL,本质还是SQL语句,只是我们可以在SQL层面,去执行一个逻辑代码
==动态SQL就是在拼接SQL语句,我们只要保证SQL的正确性,按照SQL的格式,去排列组合就可以了I=
建议:
•现在Mysq中写出完整的SQL,再对应的去修改成为我们的动态SQL实现通用即可
13、缓存
杳询:连接数据库,耗资源!
一次查询的结果,给他暂存在一个可以直接取到的地方!---->内存:缓存
我们再次查询相同数据的时候,直接走缓存,就不用走数据库
13.1简介
- 什么是缓存[ Cache ]?
。存在内存中的临时数据。
。将用户经常查询的数据放在缓存(内存)中,用户去查询数据就不用从磁盘上(关系型数据库数据文件)查询,从缓存中查询,从而提高查询效率,解决了高并发系统的性能问题。 - 为什么使用缓存?
减少和数据库的交互次数,减少系统开销,提高系统效率。 - 什么样的数据能使用缓存?
经常查询并且不经常改变的数据。
13.2Mybatis缓存
-
MyBatis包含一个非常强大的查询缓存特性,它可以非常方便地定制和配置缓存。缓存可以极大的提升查询效率。
-
MyBatis系统中默认定义了两级缓存:一级缓存和二级缓存
-
默认情况下,只有一级缓存开启。(SqlSession级别的缓存,也称为本地缓存)
-
二级缓存需要手动开启和配置,他是基于namespace级别的缓存。
-
为了提高扩展性,MyBatis定义了缓存接口Cache。我们可以通过实现Cache接口来自定义二级缓存
-
13.3、一级缓存
- 级缓存也叫本地缓存:
。与数据库同一次会话期间查询到的数据会放在本地缓存中。
。以后如果需要获取相同的数据,直接从缓存中拿,没必须再去查询数据库;
测试环境搭建
1.开启日志
2.测试在一个Sqlsession中查询两次相同的记录
package com.kuang.dao;
import com.kuang.pojo.user;
import com.kuang.utils.MybatisUtils;
import org.apache.ibatis.session.SqlSession;
import org.junit.Test;
import java.util.HashMap;
import java.util.List;
public class userDaoTest {
@Test
public void test() {
SqlSession sqlSession = MybatisUtils.getSqlSession();
userMapper userDao = sqlSession.getMapper(userMapper.class);
user user1 = userDao.getUserById(1);
System.out.println(user1);
user user2 = userDao.getUserById(1);
System.out.println(user2);
System.out.println(user1==user2);
sqlSession.close();
}
}
3.参看日志输出
缓存失效的情况:
- 增删改,可能回修改原来的东西所以必定会刷新缓存
- 查询不同的东西
- 查询不同的mapper.xml
- 手动清理缓存
小结:一级缓存默认开启,再一次Sqlsession开启
13.2二级缓存
-
二级缓存也叫全局缓存,一级缓存作用域太低了,所以诞生了二级缓存
-
基于namespace级别的缓存,一个名称空间,对应一个二级缓存;
工作机制
- 一 个会话查询
- 一 条数据,这个数据就会被放在当前会话的一级缓存中;
- 如果当前会话关闭了,这个会话对应的一级缓存就没了;但是我们想要的是,会话关闭了,一级缓存中的
- 数据被保存到二级缓存中;
- 新的会话查询信息,就可以从二级缓存中获取内容;
- 不同的mapper查出的数据会放在自己对应的缓存(map)中;
步骤:
-
开启全局缓存
-
<setting name="cacheEnabled" value="true"
-
-
测试
小结:
•只要开启了二级缓存,在同一个Mapper下就有效
•所有的数据都会先放在一级缓存中;
•只有当会话提交,或者关闭的时候,才会提交到二级缓冲中!
13.5缓存原理
13.6、自定义缓存
导包
<dependencies>
<dependency>
<groupId>org.mybatis.caches</groupId>
<artifactId>mybatis-ehcache</artifactId>
<version>1.1.0</version>
</dependency>
</dependencies>
14、实战练习
Spring
https://spring.io/
情况下,只有一级缓存开启。(SqlSession级别的缓存,也称为本地缓存)
-
二级缓存需要手动开启和配置,他是基于namespace级别的缓存。
-
为了提高扩展性,MyBatis定义了缓存接口Cache。我们可以通过实现Cache接口来自定义二级缓存
13.3、一级缓存
- 级缓存也叫本地缓存:
。与数据库同一次会话期间查询到的数据会放在本地缓存中。
。以后如果需要获取相同的数据,直接从缓存中拿,没必须再去查询数据库;
测试环境搭建
1.开启日志
2.测试在一个Sqlsession中查询两次相同的记录
package com.kuang.dao;
import com.kuang.pojo.user;
import com.kuang.utils.MybatisUtils;
import org.apache.ibatis.session.SqlSession;
import org.junit.Test;
import java.util.HashMap;
import java.util.List;
public class userDaoTest {
@Test
public void test() {
SqlSession sqlSession = MybatisUtils.getSqlSession();
userMapper userDao = sqlSession.getMapper(userMapper.class);
user user1 = userDao.getUserById(1);
System.out.println(user1);
user user2 = userDao.getUserById(1);
System.out.println(user2);
System.out.println(user1==user2);
sqlSession.close();
}
}
3.参看日志输出
[外链图片转存中…(img-fK4Yt75O-1651656024046)]
缓存失效的情况:
- 增删改,可能回修改原来的东西所以必定会刷新缓存
- 查询不同的东西
- 查询不同的mapper.xml
- 手动清理缓存
小结:一级缓存默认开启,再一次Sqlsession开启
13.2二级缓存
-
二级缓存也叫全局缓存,一级缓存作用域太低了,所以诞生了二级缓存
-
基于namespace级别的缓存,一个名称空间,对应一个二级缓存;
工作机制
- 一 个会话查询
- 一 条数据,这个数据就会被放在当前会话的一级缓存中;
- 如果当前会话关闭了,这个会话对应的一级缓存就没了;但是我们想要的是,会话关闭了,一级缓存中的
- 数据被保存到二级缓存中;
- 新的会话查询信息,就可以从二级缓存中获取内容;
- 不同的mapper查出的数据会放在自己对应的缓存(map)中;
步骤:
-
开启全局缓存
-
<setting name="cacheEnabled" value="true"
-
-
测试
小结:
•只要开启了二级缓存,在同一个Mapper下就有效
•所有的数据都会先放在一级缓存中;
•只有当会话提交,或者关闭的时候,才会提交到二级缓冲中!
13.5缓存原理
[外链图片转存中…(img-06J968ev-1651656024047)]
13.6、自定义缓存
导包
<dependencies>
<dependency>
<groupId>org.mybatis.caches</groupId>
<artifactId>mybatis-ehcache</artifactId>
<version>1.1.0</version>
</dependency>
</dependencies>
14、实战练习
Spring
https://spring.io/