1、简介
1.1、什么是mybatis
- MyBatis 是一款优秀的持久层框架,它支持自定义 SQL、存储过程以及高级映射
- MyBatis 免除了几乎所有的 JDBC 代码以及设置参数和获取结果集的工作。
- MyBatis 可以通过简单的 XML 或注解来配置和映射原始类型、接口和 Java POJO(Plain Old Java Objects,普通老式 Java 对象)为数据库中的记录。
- MyBatis本是apache的一个开源项目iBatis,2010年这个项目由apache software foundation迁移到了[google code](https://baike.baidu.com/item/google code/2346604),并且改名为MyBatis。2013年11月迁移到Github。
1.2、如何获得mybatis?
-
maven仓库
<!-- https://mvnrepository.com/artifact/org.mybatis/mybatis --> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis</artifactId> <version>3.5.2</version> </dependency>
GitHub:https://github.com/mybatis/mybatis-3
-
mybatis的中文文档:https://github.com/tuguangquan/mybatis
1.3、持久化
- 数据持久化:持久化就是将程序的数据在持久状态和瞬时状态转化的过程。“持久化”这个概念是和“暂时”等概念相对的,数据在计算机中有一般有两个存储地,内存为暂存,因为电源关机就会数据丢失,如果需要反复使用,就要持久保存,实现持久化了。
- 为什么需要持久化?
- 持久化技术封装了数据访问细节,为大部分业务逻辑提供面向对象的API。
- 通过持久化技术可以减少访问数据库数据次数,增加应用程序执行速度;
- 代码重用性高,能够完成大部分数据库操作;
- 松散耦合,使持久化不依赖于底层数据库和上层业务逻辑实现,更换数据库时只需修改配置文件而不用修改代码。
1.4、持久层(dao)
-
Dao层,Service层,Controller层
- 持久层要完成持久化的代码,并完成持久层的动作
- 三层之间的界限十分明显
-
区分持久化与持久层。
持久化相当于是一个动作,而持久层是程序设计模式中的完成持久化的一个部分。
1.5、为什么需要mybatis?
-
方便程序员将数据存到数据库中
-
是持久化操作变得更为快捷
-
传统的JDBC代码过于复杂
-
使用mybatis会使项目更容易上手
优点:
- 简单易学:本身就很小且简单。没有任何第三方依赖,最简单安装只要两个jar文件+配置几个sql映射文件。易于学习,易于使用。通过文档和源代码,可以比较完全的掌握它的设计思路和实现。
- 灵活:mybatis不会对应用程序或者数据库的现有设计强加任何影响。 sql写在xml里,便于统一管理和优化。通过sql语句可以满足操作数据库的所有需求。
- 解除sql与程序代码的耦合:通过提供DAO层,将业务逻辑和数据访问逻辑分离,使系统的设计更清晰,更易维护,更易单元测试。sql和代码的分离,提高了可维护性。
- 另外使用的人群较多。
2、第一个mybatis程序
思路:搭建环境—>导入Mybatis—>编写代码—>测试!
2.1、搭建环境
-
搭建数据库
create table `user`( `id` int(20) NOT NULL primary key, `name` varchar(30) default null, `pwd` varchar(30) default null )engine=InnoDB default char set=utf8; insert into `user`(`id`,`name`,`pwd`) values (1,'张三','8888'), (2,'李四','8888'), (3,'王五','8888')
新建项目
-
新建一个普通的maven项目
-
删除src目录
-
导入maven依赖
<dependencies> <!--MySql驱动--> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>8.0.25</version> </dependency> <!--MyBatis驱动--> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis</artifactId> <version>3.5.2</version> </dependency> <!--junit驱动--> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>4.12</version> <scope>test</scope> </dependency> </dependencies>
-
2.2、创建一个模块
-
编写核心配置文件
**注意:**核心配置文件中的Mapper组件的资源路径以/进行间隔。
<?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"> <!--mybatis的核心配置文件--> <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_test?useSSL=true&useUnicode=true&characterEncoding=UTF-8"/> <property name="username" value="root"/> <property name="password" value="abc123"/> </dataSource> </environment> </environments> <!--每一个Mapper.xml都需要在mybatis的核心配置中注册--> <!--所有的路径以斜杠结尾--> <mappers> <mapper resource="com/haha/dao/UserMapper.xml"/> </mappers> </configuration>
-
在pom文件加入以下代码防止资源导出问题
<!-- 在build中配置resources,来防止我们资源导出失败的问题-->
<build>
<resources>
<resource>
<directory>src/main/resource</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>
-
编写mybatis的工具类
每个基于 MyBatis 的应用都是以一个 SqlSessionFactory 的实例为核心的。SqlSessionFactory 的实例可以通过 SqlSessionFactoryBuilder 获得。而 SqlSessionFactoryBuilder 则可以从 XML 配置文件或一个预先配置的 Configuration 实例来构建出 SqlSessionFactory 实例。
public class MybatisUtils { private static SqlSessionFactory sqlSessionFactory; static{ try { //第一步:获取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(){ 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; } @Override public String toString() { return "User{" + "id=" + id + ", name='" + name + '\'' + ", 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; } }
-
dao接口
package com.haha.dao; import com.haha.entity.User; import java.util.List; 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" "http://mybatis.org/dtd/mybatis-3-mapper.dtd"> <!--namespace是一个命名空间绑定对应的接口--> <mapper namespace="com.haha.dao.UserDao"> <!--查询语句--> <!--id对应接口中的方法名--> <select id="getUserList" resultType="com.haha.entity.User"> select * from 'user'; </select> </mapper>
2.4、测试
-
Junit测试
public class UserMapperTest { @Test public void test(){ //1.获得sqlSession对象 SqlSession sqlSession = MybatisUtils.getSqlSession(); //方式一:执行sql UserMapper userDao = sqlSession.getMapper(UserMapper.class); List<User> userList = userDao.getUserList(); for (User user : userList) { System.out.println(user); } sqlSession.close(); } }
3、CRUD增删改查
3.1、namespace
namespace中的包名要与Dao/Mapper接口的包名一致,且以.进行间隔
<mapper namespace="com.haha.dao.UserMapper">
3.2、select
select是选择的意思表示查询语句;
- id:select标签中id指的是namespace所对应类中的方法名
- resultType:SQL语句执行时的返回值
- parameterType:指的是select语句的参数类型
3.3、insert,delete,update三操作
注意点:
- 增删改需要提交事务,事务用来管理insert,update,delete语句,即要执行上述操作时,须执行commit语句。
-
编写接口
//在表中插入一个用户 int insertUser(User user);
-
编写对应Mapper中的SQL语句
<!--插入语句--> <insert id="insertUser" parameterType="com.haha.entity.User"> insert into mybatis.user (id,name,pwd) values (#{id},#{name},#{pwd}) </insert>
-
测试
@Test //插入操作 public void insertTest(){ SqlSession sqlSession = MybatisUtils.getSqlSession(); UserMapper userMapper = sqlSession.getMapper(UserMapper.class); int i = userMapper.insertUser(new User(7, "李六", "123")); if(i>0){ System.out.println("操作成功"); } //sqlsession提交事务管理,执行一次原子操作 sqlSession.commit(); sqlSession.close(); }
3.4、常见的错误
- 标签不要匹配错误
- resource绑定Mapper,需要使用路径‘/’
- 程序的配置文件必须符合规范
- 空指针异常,没有注册到资源
- Maven资源导出问题,注意在Maven文件中添加相应的配置
3.5、万能Map(可定制化功能)
假设我们的实体类,或者数据库中的表,字段或者参数过多,我们应当考虑使用Map!
//利用万能的map在表中插入数据
int insertUser2(Map<String,Object> map);
<!--利用map在表中插入数据,参数类型是map,将map中对应的值传如SQL语句中-->
<insert id="insertUser2" parameterType="map">
insert into mybatis.user (id,name)
values (#{userId},#{userName});
</insert>
@Test
public void insertTest2(){
SqlSession sqlSession = MybatisUtils.getSqlSession();
UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
HashMap<String, Object> map = new HashMap<String, Object>();
map.put("userId",10);
map.put("userName","xuerongrong");
int i = userMapper.insertUser2(map);
if (i>0){
System.out.println("map插入成功");
}
sqlSession.commit();
sqlSession.close();
}
- Map传递参数,直接在SQL中取出key即可!(parameterType=“map”)
- 对象传递参数,直接在SQL中取对象的属性即可!(parameterType=“Object”)
- 只有一个基本类型参数的情况下,可以直接在SQL中取到
- 多个参数用Map,或者注解!
3.6、模糊查询
模糊查询怎么写?
-
Java代码执行的时候,传递通配符% %(直接在Java传参时加上通配符%)
@Test public void likeTest(){ SqlSession sqlSession = MybatisUtils.getSqlSession(); UserMapper userMapper = sqlSession.getMapper(UserMapper.class); List<User> userList = userMapper.getUserLike("%李%"); for (User user:userList ) { System.out.println(user); } sqlSession.close(); }
-
在SQL拼接中使用通配符
<!--模糊查询--> <select id="getUserLike" resultType="com.haha.entity.User"> select * from mybatis.user where name like "%"#{value}"%" </select>
4、配置解析
4.1、核心配置文件
-
mybatis-config.xml
-
MyBatis的配置文件包含了会深深影响MyBatis行为设置和属性信息
configuration(配置) properties(属性) settings(设置) typeAliases(类型别名) typeHandlers(类型处理器) objectFactory(对象工厂) plugins(插件) environments(环境配置) environment(环境变量) transactionManager(事务管理器) dataSource(数据源) databaseIdProvider(数据库厂商标识) mappers(映射器)
4.2、环境配置(environments)
MyBatis 可以配置成适应多种环境,
不过要记住:尽管可以配置多个环境,但每个 SqlSessionFactory 实例只能选择一种环境。
学会使用多套运行环境
Mybatis默认的事务管理器就是JDBC,连接池:POOLED
4.3、属性(properties)
我们可以通过properties属性来实现引用配置文件
这些属性都是可外部配置且可动态替换的,既可以在典型的Java属性文件中配置,也可以通过properties元素的子元素来传递{db.properties}
db.properties
driver=com.mysql.cj.jdbc.Driver
url=jdbc:mysql://localhost:3306/mybatis?useSSL=true&useUnicode=true&characterEncoding=UTF-8
username=root
password=abc123
在核心配置文件中引入
<properties resource="db.properties">
<property name="username" value="root"/>
<property name="password" value="abc123"/>
</properties>
- 可以直接引入外部文件
- 可以在properties标签中增加一些属性配置
- 如果两个文件有同一个字段,那么就优先使用外部配置文件的!
4.4、类型别名
-
类型别名可为 Java 类型设置一个缩写名字。
-
意在降低冗余的全限定类名书写。
<typeAliases> <typeAlias type="com.haha.entity.User" alias="User"/> </typeAliases>
也可以指定一个包名,Mybatis会在包名下面搜索需要的JavaBean,比如扫描实体类的包,它的默认别名就是这个类的类名,首字母小写!
<typeAliases>
<package name="com.haha.entity"/>
</typeAliases>
在实体类比较少的时候,使用第一种方式加别名
而如果实体类比较多,建议使用第二种,采用包名对应的方式
第一种可以自定义别名,第二种则不行,如果非要进行修改,需要在实体上增加注释
@Alias("user")
public class User {}
4.5、设置
4.6、其他设置
4.7、映射器(Mapper)
MapperRegistry:注册并绑定我们的Mapper文件
方式一:
<!--每一个Mapper.xml都需要在mybatis的核心配置中注册-->
<!--核心配置文件指向xml的所在位置,所有的路径以斜杠结尾-->
<mappers>
<mapper resource="com/haha/dao/UserMapper.xml"/>
</mappers>
方式二:使用class文件绑定注册
<!--每一个Mapper.xml都需要在mybatis的核心配置中注册-->
<!--核心配置文件指向xml的所在位置,所有的路径以斜杠结尾-->
<mappers>
<mapper class="com.haha.dao.UserMapper"/>
</mappers>
注意点:
- 接口和他的Mapper配置文件必须同名
- 接口和他的Mapper配置文件必须在同一个包下!
方式三:使用package包扫描
<!--每一个Mapper.xml都需要在mybatis的核心配置中注册-->
<!--核心配置文件指向xml的所在位置,所有的路径以斜杠结尾-->
<mappers>
<package name="com.haha.dao"/>
</mappers>
注意点:
- 接口和他的Mapper配置文件必须同名
- 接口和他的Mapper配置文件必须在同一个包下!
4.8、生命周期和作用域
作用域和生命周期类别是至关重要的,因为错误的使用会导致非常严重的并发问题。
SqlSessionFactoryBuilder:
- 一旦创建了 SqlSessionFactory,就不再需要它了。
- 因此 SqlSessionFactoryBuilder 实例的最佳作用域是方法作用域(也就是局部方法变量)
SqlSessionFactory:
- 说白了可以想象为数据库连接池
- SqlSessionFactory 一旦被创建就应该在应用的运行期间一直存在,没有任何理由丢弃它或重新创建另一个实例。
- SqlSessionFactory 的最佳作用域是应用作用域。
- 最简单的就是使用单例模式或者静态单例模式。
SqlSession:
- 相当于连接到连接池的一个请求
- sqlsession需要开启与关闭
- SqlSession 的实例不是线程安全的,因此是不能被共享的
- 最佳的作用域是请求或方法作用域。
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-mzL93yyj-1647259892881)(01_认识MyBatis.assets/image-20220302160212810.png)]
这里的每一个Mapper就代表一个具体的业务
5、解决属性名和字段名不一致的问题
5.1、问题引出
数据库中的字段
新建一个项目,拷贝之前的代码,测试实体类字段不一致的情况
public class User {
private int id;
private String name;
private String password;
测试出现的问题
解决方法:
-
起别名
<select id="getUserById" resultType="user"> select id,name,pwd as password from mybatis.user where id=#{id} </select>
5.2、resultMap
结果集映射
<!--结果集映射-->
<!--column:代表数据库表中的字段,property:代表实体类中的属性-->
<resultMap id="userMap" type="com.haha.entity.User">
<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 的优秀之处——你完全可以不用显式地配置它们。 虽然上面的例子不用显式配置 ResultMap
resultMap的简单使用
-
在配置的文件中显示的配置resultMap,讲数据库表的column字段与Java实体类的属性进行一一对应
<resultMap id="userResultMap" type="User"> <id property="id" column="user_id" /> <result property="username" column="user_name"/> <result property="password" column="hashed_password"/> </resultMap>
-
在引用它的语句中设置
resultMap
属性就行了(注意我们去掉了resultType
属性)。比如:<select id="selectUsers" resultMap="userResultMap"> select user_id, user_name, hashed_password from some_table where id = #{id} </select>
6、日志
6.1、日志工厂
如果一个数据库操作出现了异常,当我们需要排错时,日志就是我们最好的助手
过去我们用sout,debug来查找错误
现在:日志工厂
- SLF4J
- LOG4J{掌握}
- LOG4J2
- JDK_LOGGING
- COMMONS_LOGGING
- STDOUT_LOGGING{掌握}
- NO_LOGGING
在Mybatis中我们具体使用哪一个日志来实现,具体是由我们的设置决定
STDOUT_LOGGING标准日志输出(可以直接使用的)
在mybatis的核心配置文件中配置我们的日志
<settings>
<setting name="logImpl" value="STDOUT_LOGGING"/>
</settings>
6.2、LOG4J
什么是log4j?
- Log4j是Apache的一个开源项目,通过使用Log4j,我们可以控制日志信息输送的目的地是控制台、文件、GUI组件
- 我们也可以控制每一条日志的输出格式;
- 通过定义每一条日志信息的级别,我们能够更加细致地控制日志的生成过程
- 可以通过一个配置文件来灵活地进行配置,而不需要修改应用的代码。
如何使用log4j
-
先导入log4j的包
<dependency> <groupId>log4j</groupId> <artifactId>log4j</artifactId> <version>1.2.17</version> </dependency>
-
在resources文件夹下建立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/haha.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的使用,直接测试运行刚才的查询
简单使用
-
在要使用log4j的类中,导入包import org.apache.log4j.Logger;
-
日志对象加载为当前类的class对象
static Logger logger = Logger.getLogger(UserMapperTest.class);
-
日志级别
logger.info("info:进入了testLog4j"); logger.debug("debug:进入了testLog4j"); logger.error("error:进入了testLog4j");
7、分页
思考:为什么要分页?
- 减少数据的处理量
7.1、使用SQL语句的limit进行分页
sql语法 select * from user limit startIndex,pageSize;
select * from user limit 2,3
使用mybatis实现分页,核心就是SQL
-
接口
//使用limit实现分页查询 List<User> getUserByLimit(Map<String,Integer> map);
-
Mapper.xml
<select id="getUserByLimit" resultMap="userMap" parameterType="map"> select * from mybatis.user limit #{startIndex},#{pageSize} </select>
-
测试
@Test public void limitTest(){ SqlSession sqlSession = MybatisUtils.getSqlSession(); UserMapper userMapper = sqlSession.getMapper(UserMapper.class); HashMap<String, Integer> map = new HashMap<>(); map.put("startIndex",3); map.put("pageSize",5); List<User> userList = userMapper.getUserByLimit(map); for (User user: userList) { System.out.println(user); } sqlSession.close(); }
7.2、RowBounds实现分页
不在使用SQL实现分页
-
接口
//使用RowBounds实现分页查询 List<User> getUserByRowBounds(Map<String,Integer> map);
-
Mapper.xml
<!--分页查询RowBounds--> <select id="getUserByRowBounds" resultMap="usermMap"> select * from mybatis.user </select>
-
测试
@Test public void rowBoundsTest(){ SqlSession sqlSession = MybatisUtils.getSqlSession(); RowBounds rowBounds = new RowBounds(2, 3); List<User> selectList = sqlSession.selectList("com.haha.dao.UserMapper.getUserByRowBounds",null,rowBounds); for (User user:selectList) { System.out.println(user); } sqlSession.close(); }
7.3、分页插件
8、使用注解开发
8.1、面向接口编程
- 大家之前都学习过面向对象编程,也学习过接口,但在真正的开发中,很多时候我们会选择面向接口编程
- 根本原因:解耦,可拓展,提高复用,分层开发中,上层不用管具体的实现,大家都遵守共同的标准,使得开发变得容易,规范性更好
- 在一个面向对象的系统中,系统的各种功能是由许许多多的不同对象协助完成的。在这种情况下,各个对象内部是如何实现自己的,对系统设计人员来讲就不那么重要了
- 而各个对象之间的协作关系则成为系统设计的关键。小到不同类之间的通信,大道各模块之间的交互,在系统设计之初都是要着重考虑的,这也是系统设计的主要工作内容。面向接口编程就是按照这种思想来编程
关于接口的理解
-
接口从更深层次的理解,应是定义(规范、约束)与实现(名实分离的原则)的分离
-
接口的本身反映了系统设计人员对系统的抽象理解
-
接口应有两种
- 第一类是对一个个体的抽象,它可对应为一个抽象体(abstract class)
- 第二类是对一个个体某一方面的抽象,即形成一个抽象面(interface)
-
一个体可能有多个抽象面,抽象体和抽象面是有区别的
三个面向区别
- 面向对象是指,我们考虑问题时,以对象为单位,考虑它的属性及方法
- 面向过程是指,我们考虑问题时,以一个具体的流程(事务过程)为单位,考虑它的实现
- 接口设计与非接口设计是针对复用技术而言的,与面向对象(过程)不是一个问题,更多的体现就是对系统整体的架构
8.2、使用注解开发
- 使用注解来映射简单语句会使代码显得更加简洁,
- 但对于稍微复杂一点的语句,Java 注解不仅力不从心,还会让你本就复杂的 SQL 语句更加混乱不堪。
- 因此,如果你需要做一些很复杂的操作,最好用 XML 来映射语句。
注解开发
-
注解在接口上实现
@Select("select * from mybatis.user") List<User> getUser();
-
需要在核心配置文件中绑定接口文件
<!--绑定接口文件--> <mappers> <mapper class="com.haha.dao.UserMapper"/> </mappers>
-
测试
@Test public void test(){ SqlSession sqlSession = MybatisUtils.getSqlSession(); //底层主要应用反射 UserMapper userMapper = sqlSession.getMapper(UserMapper.class); List<User> userList = userMapper.getUser(); for (User user:userList ) { System.out.println(user); } sqlSession.close(); }
本质:反射机制实现
底层:动态代理
Mybatis详细执行流程
8.3、CRUD
我们可以在创建工具类的时候可以实现自动提交事务!
public static SqlSession getSqlSession(){
//设置为true则可以自动提交事务
return sqlSessionFactory.openSession(true);
}
编写接口增加注解
public interface UserMapper {
@Select("select * from mybatis.user")
List<User> getUser();
//增加一个用户
@Insert("insert into mybatis.user(id,name,pwd) values(#{id},#{name},#{password})")
int addUser(User user);
//删除用户
//方法存在多个参数必须在参数前面加上@Param("id")注解,以便框架进行识别
@Delete("delete from mybatis.user where id=#{id}")
int deleteUser(@Param("id") int id);
//修改用户信息
@Update("update mybatis.user set name=#{name},pwd=#{password} where id=#{id}")
int updateUser(User user);
//根据用户id查询用户信息
@Select("select * from mybatis.user where id=#{uid}")
int queryUser(@Param("uid") int id);
}
测试类:
注意:我们必须要将接口注册绑定到我们的核心配置文件中!
关于@Param()注解
- 基本类型的参数或者String类型,需要用该注解
- 引用类型不需要使用该注解
- 如果只有一个基本类型的参数时,可以忽略,但建议加上
- 我们在SQL中引用的就是我们这里的@Param(“uid”)中设定的属性名!
9、Lombok
Lombok项目是一个Java库,它会自动插入编辑器和构建工具中,Lombok提供了一组有用的注释,用来消除Java类中的大量样板代码。仅五个字符(@Data)就可以替换数百行代码从而产生干净,简洁且易于维护的Java类。
使用步骤:
在IDEA中安装Lombok插件
在项目中导入lombok的jar包
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.18.10</version>
<scope>provided</scope>
</dependency>
在程序上加注解
@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
10、多对一处理
例如:多个学生对应一个老师
- 对于学生而言,多个学生关联一个老师{多对一}
- 对于老师而言,集合一个老师又很多个学生{一对多}
10.1、测试环境搭建
- 新建实体类Teacher、Student
- 建立相应的Mapper接口
- 建立相应的Mapper.XML配置文件
- 在核心配置文件中绑定注册我们的Mapper接口或者文件【很多方式,自己补充】
- 测试查询是否能够成功
10.2、按照查询嵌套处理
<!--1.查询所有的学生信息
2.根据查询出来的学生的tid,寻找相对应的老师
-->
<select id="getStudent" resultMap="StudentTeacher">
select * from student
</select>
<!--解决属性名和字段名不一致的问题-->
<resultMap id="StudentTeacher" type="com.haha.entity.Student">
<!--result与id只能针对单个的结果集映射-->
<id property="id" column="id"/>
<result property="name" column="name"/>
<!--复杂的属性必须进行单独处理,association:对象(多对一),collection:集合(一对多)-->
<!--通过student的外键tid在Teacher表中进行一次嵌套查询,就是标签select-->
<association property="teacher" column="tid" javaType="com.haha.entity.Teacher" select="getTeacher"/>
</resultMap>
<select id="getTeacher" resultType="com.haha.entity.Teacher">
select * from teacher where id=#{id}
</select>
10.3、按照结果进行嵌套处理
<!--按照结果进行嵌套处理-->
<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="com.haha.entity.Student">
<id property="id" column="sid"/>
<result property="name" column="sname"/>
<association property="teacher" javaType="com.haha.entity.Teacher">
<result property="name" column="tname"/>
</association>
</resultMap>
回顾MySQL多对一查询方式
- 子查询
- 联表查询
11、一对多处理
比如:一个老师拥有多个学生!
对于老师而言就有多个学生
11.1、环境搭建
-
实体类
public class Teacher { private int id; private String name; //一个老师对应多个学生 private List<Student> students;
public class Student { private int id; private String name; private int tid;
11.2、按照SQL查询的结果嵌套处理
按照结果查询,是通过SQL语句进行查询的结果,进行resultMap映射
<!--按照结果嵌套查询-->
<select id="getTeacher" resultMap="TeacherStudent">
select t.id tid,t.name tname,s.id sid, s.name sname
from teacher t, student s
where t.id=s.tid and t.id=#{tid}
</select>
<resultMap id="TeacherStudent" type="com.haha.entity.Teacher">
<id property="id" column="tid"/>
<result property="name" column="tname"/>
<!--java=""指定属性的类型,集合中泛型的信息使用ofType获取-->
<collection property="students" ofType="com.haha.entity.Student">
<result property="name" column="sname"/>
<result property="id" column="sid"/>
<result property="tid" column="tid"/>
</collection>
</resultMap>
11.3、按照查询语句进行嵌套处理
按照查询语句查询则是先写两个查询,然后通过子查询再查一遍
<select id="getTeacher2" resultMap="TeacherStudent2">
select * from teacher where id=#{tid}
</select>
<resultMap id="TeacherStudent2" type="com.haha.entity.Teacher">
<result property="id" column="id"/>
<result property="name" column="name"/>
<collection property="students" javaType="ArrayList" ofType="Student" select="getStudentByTeacherId" column="id"/>
</resultMap>
<select id="getStudentByTeacherId" resultType="com.haha.entity.Student">
select * from student where tid=#{tid}
</select>
11.4、小结
- 关联-association【多对一的关系】
- 集合-collection【一对多的关系】
- JavaType & ofType
- JavaType 用来指定实体类中属性的类型
- ofType 用来指定映射到List或者集合中的实体类型,即泛型中的约束类型
注意点:
- 保证SQL的可读性,尽量保证通俗易懂
- 注意一对多和多对一种,属性名和字段的问题
- 如果问题不好排查,可以使用日志,建议Log4j
12、动态SQL
什么是动态SQL:动态SQL就是指根据不同的条件生成不同的SQL语句
利用动态SQL语句可以摆脱拼接SQL语句的痛苦
搭建环境
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
创建一个基础工程
-
导包
-
编写配置文件
-
编写实体类
public class Blog { private int id; private String title; private String author; private Date createTime; private int views;
-
编写实体类对应的Mapper接口和Mapper.xml文件
12.1、IF
<select id="queryListIF" parameterType="map" resultType="com.haha.entity.Blog">
select * from blog where 1=1
<if test="title!=NUll">
and title=#{title}
</if>
<if test="author!=NUll">
and author=#{author}
</if>
<if test="views!=null">
and views>#{views}
</if>
</select>
注意:
未使用转义字符
在使用了mybatis的过程中,在动态SQL语句的部分如果有对数值大小的判断,不能直接用大于小于号,需要在xml文件中用转义字符> ;(大于) < ;(小于) > ; =(大于等于) < ;<(小于等于)
使用转义字符之后:
12.2、choose、when、otherwise、
<select id="queryListChoose" parameterType="map" resultType="com.haha.entity.Blog">
select * from blog
<where>
<choose>
<when test="title!=null">
title=#{title}
</when>
<when test="author!=null">
and author=#{author}
</when>
<otherwise>
views >=#{views}
</otherwise>
</choose>
</where>
</select>
12.3、trim、where、set
思考:在之前的例子中where后衔接的是一个静态的判断语句,当我们转换成动态的语句时,如果where的语句不成立,那么后面拼接的语句就会成为以下格式
select * from blog
where
and title=#{title}
因为动态SQL语句在拼接的时候哦出现了错误,这个查询也会失败。这个问题不能简单地用条件元素来解决。
MyBatis 有一个简单且适合大多数场景的解决办法。就是在配置文件中使用的元素标签,where 元素只会在至少有一个子元素返回任何内容的情况下才插入 “WHERE” 子句。而且,若子句的开头为 “AND” 或 “OR”,where 元素也会将它们去除。
where
<select id="queryListChoose" parameterType="map" resultType="com.haha.entity.Blog">
select * from blog
<where>
<choose>
<when test="title!=null">
title=#{title}
</when>
<when test="author!=null">
and author=#{author}
</when>
<otherwise>
views >=#{views}
</otherwise>
</choose>
</where>
</select>
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>
所谓的动态SQL,本质还是SQL语句,只是我们可以在SQL层面去执行一个逻辑代码
trim
SQL片段
有时候,我们可能会将一些功能部分抽取出来方便复用
-
使用SQL标签抽取公共的部分
<sql id="queryListIFSQL"> <if test="title!=NUll"> and title=#{title} </if> <if test="author!=NUll"> and author=#{author} </if> <if test="views!=null"> and views >#{views} </if> </sql>
-
在需要使用的地方引入include标签即可
<select id="queryListIF" parameterType="map" resultType="com.haha.entity.Blog"> select * from blog <where> <include refid="queryListIFSQL"></include> </where> </select>
注意事项:
- 最好基于单表来定义SQL片段!
- 不要存在where标签
12.4、Foreach
注意SQL语句的空格
动态SQL:
<!--
select * from mybatis.blog where 1=1 and (id=1 or id=2 or id=3)
-->
<!--注意SQL语句的空格-->
<select id="queryBlogForeach" parameterType="map" resultType="com.haha.entity.Blog">
select * from blog
<where>
<foreach collection="ids" item="id" open="and (" separator="or" close=")">
id=#{id}
</foreach>
</where>
</select>
动态SQL就是在拼接SQL语句,我们只要保证SQL的正确性,按照SQL的格式,去排列组合就可以了
建议:
- 先在mysql中写出完整的SQL,再对应修改成为我们的SQL并实现通用
13、缓存
13.1、简介
- 什么是缓存[Cache]?
- 存在内存中的临时数据
- 将用户经常查询的数据放在缓存(内存)中,用户去查询数据就不用从磁盘上(关系型数据库文件)查询,从缓存中查询,从而提高查询效率,解决了高并发系统的性能问题
- 为什么使用缓存?
- 减少和数据库的交互次数,减少系统开销,提高系统效率
- 什么样的数据可以使用缓存?
- 经常查询并且不经常改变的数据 【可以使用缓存】
13.2、Mybatis缓存
- MyBatis包含一个非常强大的查询缓存特性,它可以非常方便的定制和配置缓存,缓存可以极大的提高查询效率。
- MyBatis系统中默认定义了两级缓存:一级缓存和二级缓存
- 默认情况下,只有一级缓存开启(SqlSession级别的缓存,也称为本地缓存)
- 二级缓存需要手动开启和配置,他是基于namespace级别的缓存。
- 为了提高可扩展性,MyBatis定义了缓存接口Cache。我们可以通过实现Cache接口来定义二级缓存。
13.3、一级缓存
- 一级缓存也叫本地缓存:SqlSession
- 与数据库同一次会话期间查询到的数据会放在本地缓存中
- 以后如果需要获取相同的数据,直接从缓存中拿,没必要再去查询数据库
测试步骤:
-
开启日志
-
测试一个session中查询两次的记录
@Test public void queryUserByIdTest(){ SqlSession sqlSession = MybatisUtils.getSqlSession(); UserMapper userMapper = sqlSession.getMapper(UserMapper.class); User user = userMapper.queryUserById(1); System.out.println(user); System.out.println("===========================分隔线==========================="); User user2 = userMapper.queryUserById(1); System.out.println(user2); System.out.println(user==user2); sqlSession.close(); }
缓存失效的情况:
-
映射语句文件中的所有 select 语句的结果将会被缓存(即二次查询会覆盖第一次查询的缓存)。
-
映射语句文件中的所有 insert、update 和 delete 语句会刷新缓存。(即增删改操作有可能会改变之前的东西,所以系统自动刷新缓存)
-
查询不同的Mapper.xml
-
手动清理缓存
@Test public void queryUserByIdTest(){ SqlSession sqlSession = MybatisUtils.getSqlSession(); UserMapper userMapper = sqlSession.getMapper(UserMapper.class); User user = userMapper.queryUserById(1); System.out.println(user); sqlSession.clearCache(); System.out.println("===========================分隔线==========================="); User user2 = userMapper.queryUserById(1); System.out.println(user2); System.out.println(user==user2); sqlSession.close(); }
小结:一级缓存默认是开启的,只在一次SqlSession中生效,也就是拿到连接到关闭连接的这个区间段!(一级缓存相当于一个Map)
13.4、二级缓存
- 二级缓存也叫全局缓存,一级缓存作用域太低了,所以诞生了二级缓存
- 基于namespace级别的缓存,一个名称空间,对应一个二级缓存
- 工作机制
- 一个会话查询一条数据,这个数据就会被放在当前会话的一级缓存中
- 如果会话关闭了,这个会话对应的一级缓存就没了;但是我们想要的是,会话关闭了,一级缓存中的数据被保存到二级缓存中
- 新的会话查询信息,就可以从二级缓存中获取内容
- 不同的mapper查询出的数据会放在自己对应的缓存(map)中
步骤:
-
在核心配置文件中开启全局缓存
<!--显示的开启全局缓存--> <setting name="cacheEnabled" value="true"/>
-
在要使用二级缓存的Mapper中开启
<cache/>
也可以自定义参数
<cache eviction="FIFO" flushInterval="60000" size="512" readOnly="true"/>
-
测试
- 问题:我们需要将实体类序列化!否则就会报错
小结:
- 只要开启了二级缓存,在同一个Mapper下就有效!
- 所有的数据都会先放在一级缓存中;
- 只有当会话提交,或者关闭时,才会提交到二级缓存中!
13.5、缓存原理
缓存顺序:
- 先看二级缓存中有没有待搜索信息
- 二级缓存中若没有,则从一级缓存中查找
- 一级缓存中没有,则查询数据库中的数据
13.6、自定义缓存ehcache
ehcache是一个广泛使用的开源Java分布式缓存,主要面向通用缓存
<dependency>
<groupId>org.mybatis.caches</groupId>
<artifactId>mybatis-ehcache</artifactId>
<version>1.2.1</version>
</dependency>
<cache type="org.mybatis.caches.ehcache.EhcacheCache"/>