Mybatis
1.运行第一个mybatis程序
1.1导入
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.47</version>
</dependency>
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.5.7</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
</dependency>
1.2创建一个模块
-
编写mybatis核心配置文件.xml
-
<?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config 3.0//EN" "http://mybatis.org/dtd/mybatis-3-config.dtd"> <configuration> <environments default="development"> <environment id="development"> <transactionManager type="JDBC"/> <dataSource type="POOLED"> <property name="driver" value="com.mysql.jdbc.Driver"/> <property name="url" value="jdbc:mysql://localhost:3306/mybatis?useSSL=true&useUnicode=true&characterEncoding=UTF-8"/> <property name="username" value="root"/> <property name="password" value="root"/> </dataSource> </environment> </environments> <mappers> <mapper resource="UserMapper.xml"/> </mappers> </configuration>
-
编写mybatis工具类
public class MybatisUtils { private static SqlSessionFactory sqlSessionFactory ; static {//加入static用于优化性能,类被创建后只执行一次 try {//使用mybatis的第一步 获取sqlsessionfactory对象 String resource = "mybatis-config.xml"; InputStream inputStream = Resources.getResourceAsStream(resource); sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream); } catch (IOException e) { e.printStackTrace(); } } public static SqlSession getSqlSession(){ return sqlSessionFactory.openSession(); } }
1.3 编写代码
-
实体类
package com.ding.pojo; public class User { private int id; private String name; private String pwd; 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; } public int getId() { return id; } public void setId(int id) { this.id = id; } public User() { } public User(int id, String name, String pwd) { this.id = id; this.name = name; this.pwd = pwd; } }
-
Dao接口
public interface UserDao { List<User> getUserList(); }
-
接口实现类(Mapper配置文件)
每一个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绑定一个Dao接口-->
<mapper namespace="com.ding.dao.UserDao">
<select id="getUserList" resultType="com.ding.pojo.User">
select * from user;
</select>
</mapper>
1.4测试
使用Junit来对源文件进行测试
2.增删改查
2.1 namespace
namespace中包名须与接口内包名一致
2.2 select
选择、查询语句
-
id:就是对应的namespace中的方法名
-
resultType:Sql语句执行的返回值
-
parameterType:参数类型
1、编写接口
User getUserById(int id);
2、编写对应的mapper中的sql语句
<select id="getUserById" parameterType="int" resultType="com.ding.pojo.User"> select * from user where id = #{id}; </select>
3、测试
SqlSession sqlSession = MybatisUtils.getSqlSession(); UserMapper mapper = sqlSession.getMapper(UserMapper.class); System.out.println(mapper.getUserById(1).toString()); sqlSession.close();
2.3 Insert
增加记录语句
-
id:就是对应的namespace中的方法名
-
parameterType:参数类型
1、编写接口
<insert id="insertUser" parameterType="com.ding.pojo.User" >
insert into user (id,name,pwd) values (#{id},#{name},#{pwd});
</insert>
2、编写对应Mapper的sql语句
<insert id="insertUser" parameterType="com.ding.pojo.User" >
insert into user (id,name,pwd) values (#{id},#{name},#{pwd});
</insert>
3、测试
@Test
public void test2(){
SqlSession sqlSession = MybatisUtils.getSqlSession();
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
System.out.println(mapper.insertUser(new User(2,"xiaogang","2333")));
sqlSession.commit();//增删改需要提交事务
sqlSession.close();
}
2.4 update
对记录进行更新的语句
-
id:就是对应的namespace中的方法名
-
parameterType:参数类型
1、编写接口
int updateUser(User u);
2、编写对应Mapper的sql语句
<update id="updateUser" parameterType="com.ding.pojo.User">
update user set name=#{name},pwd=#{pwd} where id=#{id};
</update>
3、测试
@Test
public void test3(){
SqlSession sqlSession = MybatisUtils.getSqlSession();
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
System.out.println(mapper.updateUser(new User(2,"xiaod","23332323")));
sqlSession.commit();//增删改操作需提交事务
sqlSession.close();
}
2.5 delete
对特定记录进行删除操作
-
id:就是对应的namespace中的方法名
-
parameterType:参数类型
1、编写接口
int deleteUser(int id);
2、编写对应Mapper的sql语句
<delete id="deleteUser" parameterType="int">
delete from user where id = #{id};
</delete>
3、测试
@Test
public void test4(){
SqlSession sqlSession = MybatisUtils.getSqlSession();
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
System.out.println(mapper.deleteUser(1));
sqlSession.commit();
sqlSession.close();
}
all in all 增删改需要提交事务
2.6 map
利用map进行传值操作
假设我们的实体类,或者数据库中的表,字段或者参数过多,我们应当考虑使用map
2.7模糊查询
1.java代码执行的时候,传递通配符%%
2.在sql拼接时使用通配符!
like "%"#{value}"%"
3.配置解析
3.1、核心配置文件
-
mybatis-config.xml
properties(属性) settings(设置) typeAliases(类型别名) typeHandlers(类型处理器) objectFactory(对象工厂) plugins(插件) environments(环境配置) environment(环境变量) transactionManager(事务管理器) dataSource(数据源) databaseIdProvider(数据库厂商标识) mappers(映射器)
3.2、环境配置(environments)
尽管能够配置多个环境,但每个sqlsessionfactory实例只能选择一个环境
学习使用配置多套运行环境
Mybatis默认的事务管理器就是JDBC,连接池:POOLED
3.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=root
在核心配置文件中引入(只能放在configuration中的最前面的位置)
<properties resource="db.properties"/>
- 可以直接引入外部文件
- 可以在其中增加一些属性配置
- 如果两个文件有同一个字段,优先使用外部配置文件
3.4、类型别名(typeAliases)
-
类型别名是为java类型设置一个短的名字
-
存在的意义仅在于用于减少类完全限定名的冗余
-
<!-- 可以给实体类起别名--> <typeAliases> <typeAlias type="com.ding.pojo.User" alias="User"/> </typeAliases>
-
也可以指定一个包名,Mybatis会在包名下面搜索需要的javabean,例如:扫描实体类的包,它的默认别名就为这个类的类名,首字母小写
<!--可以给实体类起别名--> <typeAliases> <package name="com.ding.pojo"/> </typeAliases>
实体类较少建议使用第一种(且可以diy)
实体类较多建议使用第二种
如果第二种需要改名称可在实体类添加注解
@Alias("User") public class User{}
3.5、设置(settings)
3.6、其他配置
-
typeHanlers(类型处理器)
-
objectFactory(对象工厂)
-
plugins插件
- mybatis-generator-core
- Mybatis plus
3.7、映射器(mappers)
MapperRegistry:注册绑定我们的Mapper文件
方式一:
<!--每一个Mapper.xml都需要在Mybatis核心配置文件中注册-->
<mappers>
<mapper resource="UserMapper.xml"/>
</mappers>
方式二:使用class文件绑定注册
<mappers>
<mapper class="com.ding.mapper.UserMapper"/>
</mappers>
注意点:
- 接口和他的Mapper配置文件必须同名!
- 接口和他的Mapper配置文件必须在同一个包下!
方式三:
<mappers>
<package name="com.ding.mapper"/>
</mappers>
注意点:
- 与方式二注意点一致
3.8、生命周期和作用域
生命周期和作用域,是至关重要的,因为错误的使用会导致非常严重的并发问题
SqlSessionFactoryBuilder:
- 一旦创建完SqlSessionFactory后,就不再需要它了
- 局部变量
SqlSessionFactory
- 可以看作数据库的连接池
- SqlSessionFactory一旦被创建就应该在应用的运行期间一直存在,没有任何理由丢弃它或重新创建另一个实例
- 因此SqlSessionFactory的最佳作用域是应用作用域
- 最简单的就是使用单例模式或者静态单例模式
SqlSession
- 连接到连接池的一个请求
- SqlSession的实例不是线程安全的,因此不能被共享,所以它的最佳的作用域是请求或方法作用域
- 用完之后需要赶紧关闭,否则资源被占用
4.解决属性名和字段名不一致的问题
- 解决方法1:起别名
- 解决方法2:resultmap
结果集映射
<!-- 结果集映射-->
<resultMap id="UserMap" type="User">
<!-- column代表数据库中的每列-->
<!-- property代表实体类中的对应属性值-->
<result column="pwd" property="password"/>
<!--什么不同映射什么-->
</resultMap>
<!--使用resultMap-->
<select id="getUserList" resultMap="UserMap">
select * from user;
</select>
resultmap元素是MyBatis中最重要最强大的元素
ResultMap的设计思想是,对于简单的语句根本不需要配置显式的结果映射,而对于复杂一点的语句只需要描述它们的关系就行了
ResultMap优秀之处在于,虽然你已经对它相当的了解,但是你不需要显式的用到他们
如果一切总是那么简单就好了(至理名言)
5.日志
5.1、日志工厂
如果一个数据库操作出现了异常,我们需要排错,那么日志就是我们最好的助手
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-TKkmE0SZ-1625968595100)(C:\Users\86133\AppData\Roaming\Typora\typora-user-images\image-20210709091914965.png)]
具体使用哪个日志实现视情况而定
STDOUT_LOGGING 标准日志输出
<settings>
<setting name="logImpl" value="STDOUT_LOGGING"/>
</settings>
5.2 、LOG4J
1、先导包(在maven中导入)
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/ding.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、将mybatis核心配置文件中的日志改为"LOG4J"
<settings>
<setting name="logImpl" value="LOG4J"/>
</settings>
4、Log4j的使用,直接测试运行即可
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-DJ0v7Icu-1625968595103)(C:\Users\86133\AppData\Roaming\Typora\typora-user-images\image-20210709102919811.png)]
简单使用
1、在要使用log4j的类中导入包 import org.apache.log4j.Logger;
2、日志对象参数为当前类的class
static Logger logger = Logger.getLogger(UserMapperTest.class);
3、日志级别
info debug errror
6、分页
为什么要分页?
- 减少数据的处理量
6.1使用Limit分页
语法:select * from user limit startIndex,pageSize
select * from user limit 3; #[0,n)
使用Mybatis实现分页,核心sql
<select id="limitGetUser" parameterType="map" resultMap="UserMap">
select * from user limit #{start} , #{size};
</select>
使用范例
@Test
public void test3(){
SqlSession sqlSession = MybatisUtils.getSqlSession();
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
HashMap<String, Integer> map = new HashMap<>();
map.put("start",0);
map.put("size",0);
List<User> userList = mapper.limitGetUser(map);
for (User u : userList) {
System.out.println(u.toString());
}
sqlSession.close();
}
6.2 分页插件
pagehelper
7、使用注解开发
1.注解在接口上实现
@Select("select * from user;")
List<User> getUserList();
2.需要在核心配置文件上绑定接口
<!-- 绑定接口-->
<mappers>
<mapper class="com.ding.mapper.UserMapper"/>
</mappers>
3.测试使用
本质:反射机制实现
底层:动态代理
etSqlSession();
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
HashMap<String, Integer> map = new HashMap<>();
map.put(“start”,0);
map.put(“size”,0);
List userList = mapper.limitGetUser(map);
for (User u : userList) {
System.out.println(u.toString());
}
sqlSession.close();
}
### 6.2 分页插件
**pagehelper**
## 7、使用注解开发
1.注解在接口上实现
```java
@Select("select * from user;")
List<User> getUserList();
2.需要在核心配置文件上绑定接口
<!-- 绑定接口-->
<mappers>
<mapper class="com.ding.mapper.UserMapper"/>
</mappers>
3.测试使用
本质:反射机制实现
底层:动态代理
8、使用lombok
1、添加依赖
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.18.20</version>
<scope>provided</scope>
</dependency>
2、在项目中导入相应包
3、使用 例如:
package com.ding.pojo;
import lombok.Data;
public @Data class User {
private int id;
private String name;
private String pwd;
}
这样即可自动构造getter,setter方法构造器等等东西
除此之外,lombok可用的注解还有
@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
Code inspections
Refactoring actions (lombok and delombok)
8.1、注意
lombok虽然给我们带来了相应的便利,但是这东西有可能改变我们的编码习惯,因此最好不要一直用它,毕竟有句话说得好
一时用一时爽,一直用不一定一直爽
9、多对一处理
9.1、测试环境搭建
1、导入lombok(可选)
2、新建实体类Teacher与Student
3、建立Mapper接口
4、建立Mapper.xml
5、在核心配置文件中绑定注册我们的Mapper接口或文件
6、测试查询是否能够成功
9.2、按照查询嵌套处理
<select id="getStudentList" resultMap="StudentAndTeacher">
select * from student;
</select>
<resultMap id="StudentAndTeacher" type="com.ding.pojo.Student">
<result property="id" column="id"/>
<result property="name" column="name"/>
<!-- 复杂的属性需要单独处理
对象:association
集合:collection
-->
<association property="teacher" column="tid" javaType="com.ding.pojo.Teacher" select="getTeacher"/>
</resultMap>
<select id="getTeacher" resultType="com.ding.pojo.Teacher">
select * from teacher where id = #{id};
</select>
9.3、按照结果嵌套处理
<!-- 按照结果嵌套处理-->
<select id="getStudentList2" resultMap="StudentAndTeacher2">
select s.id sid,s.name sname,t.name tname from student s,teacher t where t.id = s.tid
</select>
<resultMap id="StudentAndTeacher2" type="Student">
<result property="id" column="sid"/>
<result property="name" column="sname"/>
<association property="teacher" javaType="Teacher">
<result property="name" column="tname"/>
</association>
</resultMap>
10、一对多处理
10.1、实体类
student类
public @Data class Student {
private int id;
private String name;
private int tid;
}
teacher类
public @Data class Teacher {
private int id;
private String name;
//一个老师多个学生
private Student student;
}
10.2、按结果嵌套处理
<select id="getTeacher" resultMap="TeacherAndStudent">
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="TeacherAndStudent" 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>
10.3、按查询嵌套处理
<select id="getTeacher2" resultMap="TeacherAndStudent2">
select * from teacher where id = #{tid}
</select>
<resultMap id="TeacherAndStudent2" 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>
总而言之,还是按结果嵌套处理比较容易理解。
尽量保证sql的可读性
11、动态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_tima` datetime not null COMMENT '创建时间',
`views` INT(30) not null COMMENT '浏览量'
)ENGINE=INNODB DEFAULT CHARSET=utf8
11.1、IF
<if test="title!=null">
and title=#{title}
</if>
<if test="author!=null">
and author=#{author}
</if>
11.2、Choose
类似于java中的switch语句
<select id="queryBlogChoose" parameterType="map" resultType="Blog">
select * from blog
<where>
<choose>
<when test="title!=null">
and title=#{title}
</when>
<when test="author!=null">
and author=#{author}
</when>
<otherwise>
</otherwise>
</choose>
</where>
</select>
11.3、trim
<update id="updateBlog" parameterType="map">
update blog
<set>
<if test="title!=null">
title=#{title},
</if>
<if test="author!=null">
suthor = #{author}
</if>
</set>
where id = #{id}
</update>
通过合理编写trim则可以代替set
以下是trim的参数
prefix 给sql语句拼接的前缀
suffix 给sql语句拼接的后缀
prefixOverrides 去除sql语句前面的关键字或者字符,该关键字或者字符由prefixOverrides属性指定,假设该属性指定为"AND",当sql语句的开头为"AND",trim标签将会去除该"AND"
suffixOverrides 去除sql语句后面的关键字或者字符,该关键字或者字符由suffixOverrides属性指定
11.4、SQL片段
有的时候我们可能将sql中某些片段抽取出来方便复用
<sql id="ifta">
<if test="title!=null">
and title=#{title}
</if>
<if test="author!=null">
and author=#{author}
</if>
</sql>
用sql标签包住要复用的内容
<include refid="ifta"></include>
用include标签进行引用
注意事项:
-
最好基于单表来定义SQL片段
-
不要存在where标签
11.5、foreach
用于遍历集合
<select id="queryBlogForeach" parameterType="map" resultType="Blog">
select * from Blog
<where>
<foreach collection="ids" item="id" open="and (" close=")" separator="or">
id = #{id}
</foreach>
</where>
</select>
12、缓存
12.1、简介
12.1.1、什么是缓存
- 存在内存中的临时数据
- 将用户经常查询的数据放在缓存中,用户去查询数据就不用从磁盘上查询,从缓存中查询,从而提高查询效率,解决了高并发系统的性能问题
12.1.2、为什么要使用缓存
- 减少和数据库的交互次数,减少系统开销,提高系统效率
12.1.3、什么样的数据能使用缓存
- 经常查询并且不常改变的数据
13.2、Mybatis缓存
- Mybatis包含一个非常强大的查询缓存特性,它可以非常方便地定制和配置缓存。缓存可以极大的提升查询效率。
- Mybatis系统中默认定义了两级缓存:一级缓存和二级缓存
- 默认情况下只有一级缓存开启(SqlSession级别的缓存,也称为本地缓存)
- 二级缓存需要手动开启和配置,他是基于namespace级别的缓存
- 未来提高拓展性,Mybatis定义了缓存接口Cache。我们可以通过实现Cache接口来自定义二级缓存
13.3、一级缓存
- 一级缓存也叫本地缓存:SqlSession
- 与数据库同一次会话期间查询到的数据会放在本地缓存
- 以后如果需要获取相同的数据,直接从缓存中拿,没必要再去查询数据库
测试步骤:
1、开启日志
2、测试在同一个Session同一sql语句是否执行了两次,若只有一次,那么用到了缓存
缓存失效的情况:
1、增删改操作,可能会改变原来的数据,所以必定会刷新缓存
2、查询不同的东西
3、查询不同的Mapper.xml
4、手动清理缓存
小结:一级缓存默认是开启的,只在一次SqlSession中有效,也就是拿到连接到关闭连接这个时间段内。
13.4、 二级缓存
- 二级缓存也叫全局缓存,一级缓存作用域太低了,所以诞生了二级缓存
- 基于namespace级别的缓存,一个名称空间,对应一个二级缓存
- 工作机制
- 一个会话查询一条数据,这个数据就会被放在当前会话的一级缓存中
- 如果当前会话关闭了,这个会话对应的一级缓存就没了,但是我们想要的是,会话关闭了,一级缓存中的数据被保存到二级缓存中
- 新的会话查询信息,就可以从二级缓存中获取内容
- 不同的mapper查出的数据会放在自己对应的缓存中
如何开启?
步骤:
- 前提:在mybatis-config.xml中添加
开启全局缓存
<setting name="cacheEnabled" value="true"/>
- 而后在你的Mapper.xml中添加
在当前mapper开启二级缓存
<cache/>
同时也由更高级选项,在内添加
小结:
- 只要开启了二级缓存,在同一个mapper下就有效
- 所有的数据都会先放在一级缓存中
- 只有当会话提交,或者关闭的时候,才会提交到二级缓存中