1、什么是框架?
它是我们软件开发中的一套解决方案,不同的框架解决的是不同的问题
使用框架的好处:
它封装了很多的细节,使开发者可以使用极简的方式实现功能。大大提高开发效率。
2、三层架构
表现层:
是用于展示数据的
业务层:
是处理业务需求
持久层:
是和数据库交互的
3、持久层技术解决方案:
JDBC技术:
Connection
PreparedStatement
ResultSet
Spring的JdbcTemplate:
Spring中对jdbc的简单封装
Apache的DBUtils:
它和Spring的JdbcTemplate很像,也是对Jdbc的简单封装
以上这些都不是框架
JDBC是规范
JdbcTemplate和DBUtils都只是工具类
数据持久化
持久化就是将程序的数据在持久状态和瞬时状态转化的过程
内存:断电即失
数据库(jdbc),io文件持久化
4、mybatis的概述
mybatis是一个持久层框架,用java编写的。
它封装了jdbc操作的很多细节,使开发者只需要关注sql语句本身,而无需关注注册驱动,创建连接等繁杂过程
它使用了ORM思想实现了结果集的封装
ORM:
Object Relational Mapping对象关系映射
简单说:就是把数据库和实体类及实体类的属性对应起来
让我们可以操作实体类就实现操作数据库表。
5、第一个mybatis程序
思路:搭建环境->导入mybatis->编写代码->测试
5.1搭建环境
搭建数据库
新建项目
1、新建一个普通的maven项目
2、删除src目录
3、导入maven依赖
5.2创建一个模块
编写mybatis的核心配置文件
<?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"></transactionManager>
<dataSource type="POOLED">
<property name="driver" value="com.mysql.jdbc.Driver"/>
<property name="url" value="jdbc:mysql://localhost:3306/mybatis?useUnicode=true&characterEncoding=utf-8"/>
<property name="username" value="root"/>
<property name="password" value="1318579525"/>
</dataSource>
</environment>
</environments>
</configuration>
编写mybatis工具类
public class MybatisUtils {
private static SqlSessionFactory sqlSessionFactory;
static {
try {
//使用Mybatis第一步:获取sqlSessionFactory对象
String resource = "mybatis-config.xml";
InputStream inputStream = Resources.getResourceAsStream(resource);
sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
} catch (IOException e) {
e.printStackTrace();
}
}
public static SqlSession getSqlSession(){
return sqlSessionFactory.openSession();
}
}
5.3编写代码(实体类,接口,实现类用配置文件)
5.4测试
junit
需要在核心配置文件中注册mappers
6、CRUD
6.1、namespace
namespace中的包名要和Dao/Mapper接口的包名一致
6.2、select
选择,查询语句
id:就是对应的namespace中的方法名;
resultType:Sql语句执行的返回值
parameterType:参数类型
(1)编写接口
//根据id查询用户
User getUserById(int id);
(2)编写对应mapper中的sql语句
<select id="getUserById" parameterType="int" resultType="com.cs.pojo.User">
select * from user where id = #{id}
</select>
(3)测试(增删改需要提交事务sqlsession.commit)
7、万能Map
假设,我们的实体类,或者数据库中的类,字段或者参数过多,我们应当考虑使用Map!
//万能map
int addUser2(Map<String,Object>map);
Map传递参数,直接在sql中取出key即可
对象传递参数,直接在sql中取对象的属性即可
只有一个基本类型参数的情况下,可以直接在sql中取到
多个参数用Map,或者注解
模糊查询like
%李%或者“%”#{value}“%”
8、配置解析
8.1核心配置文件
mybatis-config.xml
MyBatis的配置文件包含了会深深影响Mybatis行为的设置和属性信息
8.2环境配置(environments)
Mybatis可以配置成适应多种环境
不过要记住:尽管可以配置多个环境,但每个SqlSessionFactory实例只能选择一种环境。
学会使用配置多套运行环境
mybatis默认的事务管理器就是JDBC,连接池:POOLED
8.3属性(properties)
我们可以通过properties属性来实现引用配置文件
这些属性都是可外部配置且可动态替换的,即可以在典型的java属性文件中配置,亦可通过properties元素的子元素来传递(db.properties)
编写一个配置文件
db.properties
driver=com.mysql.jdbc.Driver
url=jdbc:mysql://localhost:3306/mybatis?useUnicode=true&characterEncoding=utf-8
username=root
password=1318579525
在核心配置文件中引入
<properties resource="db.properties">
<property name="username" value="root"/>
<property name="password" value="1318579525"/>
</properties>
可以直接引入外部文件
可以在其中增加一些属性配置
如果两个文件有同一个字段,优先使用外部配置文件的!
9、类型别名(typeAliases)
类型别名是为java类型设置一个短的名字
存在意义仅在于用来减少类完全限定名的冗余
<typeAliases>
<typeAlias type="com.cs.pojo.User" alias="User"/>
</typeAliases>
也可以指定一个包名,mybatis会在包名下面搜索需要的java Bean,比如:
扫描实体类的包,它的默认别名就为这个类的类名首字母小写
<typeAliases>
<package name="com.cs.pojo"/>
</typeAliases>
在实体类比较少的时候,使用第一种方式
如果实体类十分多,建议使用第二种
第一种可以DIY别名,第二种则不行,如果非要改,需要在实体类上增加注解
@Alias("user")
public class User {
10、设置(setting)
这是mybatis中极为重要的调整设置,他们会改变mybatis的运行时行为
11、其他配置
typeHandlers(类型处理器)
objectFactory(对象工厂)
plugins插件(mybatis-generator-core,mybatis-plus,通用mapper)
12、映射器(mappers)
MapperRegistry:注册绑定我们的mapper文件;
方式一:
<mappers>
<mapper resource="com/cs/dao/UserMapper.xml"></mapper>
</mappers>
方式二:使用class文件绑定注册
<mappers>
<mapper class="com.cs.dao.UserMapper"></mapper>
</mappers>
注意点:
接口和他的mapper配置文件必须同名
接口和他的mapper配置文件必须在同一个包下
方式三:使用扫描包进行注入绑定
<mappers>
<package name="com.cs.dao.UserMapper"/>
</mappers>
注意点:
接口和他的mapper配置文件必须同名
接口和他的mapper配置文件必须在同一个包下
13、生命周期和作用域
生命周期和作用域是至关重要的,因为错误的使用会导致非常严重的并发问题
SqlSessionFactoryBuilder:
一旦创建了SqlSessionFactory,就不再需要它了
局部变量
SqlSessionFactory:
说白了就是可以想象为:数据库连接池
SqlSessionFactory一旦被创建就应该在应用的运行期间一直存在,没有任何理由丢弃它或重新创建另一个实例。
因此SqlSessionFactory的最佳作用域是应用作用域。
最简单的就是使用单例模式或者静态单例模式
SqlSession:
连接到连接池的一个请求
Sqlsession的实例不是线程安全的,因此是不能被共享的,所以它的最佳作用域是请求或方法作用域
用完之后需要赶紧关闭,否则资源被占用!
这里面的每一个Mapper,就代表一个具体的业务
14、解决属性名和字段名不一致的问题(ResultMap)
14.1问题
新建一个项目,测试实体类字段不一致的情况
public class User {
private int id;
private String name;
private String password;
}
测试出现问题
User{id=1, name='狂神', password='null'}
解决方法:
起别名
<select id="getUserById" parameterType="int" resultType="user">
select id,name,pwd as password from user where id = #{id}
<select>
14.2ResultMap
id name pwd
id name password
<!--结果集映射-->
<resultMap id="UserMap" type="User">
<!--column数据库中的字段,property实体类中的属性-->
<result column="id" property="id"/>
<result column="name" property="name"/>
<result column="pwd" property="password"/>
</resultMap>
<select id="getUserById" parameterType="int" resultMap="UserMap">
select * from user where id = #{id}
</select>
resultMap元素是mybatis中最重要最强大的元素
ResultMap的设计思想是,对于简单的语句根本不需要配置显示的结果映射,而对于复杂一点的语句只需要描述它们的关系就行了
ResultMap最优秀的地方在于,虽然你已经对他相当了解了,但是根本就不需要显示地用到它们。
15、日志
15.1日志工厂
如果一个数据库操作,出现了异常,我们需要排错。日志就是最好的助手!
曾经:sout,debug
现在:日志工厂logImpl
掌握:LOG4j,STDOUT_LOGGING
在mybatis中具体使用哪一个日志实现,在设置中设定!
STDOUT_LOGGING标准日志输出
在mybatis核心配置文件中,配置我们的日志!
输出为:
Opening JDBC Connection
Created connection 24755078.
Setting autocommit to false on JDBC Connection [com.mysql.jdbc.JDBC4Connection@179bb86]
> Preparing: select * from user where id = ?
> Parameters: 1(Integer)
< Columns: id, name, pwd
< Row: 1, 狂神, 123456
<== Total: 1
User{id=1, name=‘狂神’, password=‘123456’}
Resetting autocommit to true on JDBC Connection [com.mysql.jdbc.JDBC4Connection@179bb86]
Closing JDBC Connection [com.mysql.jdbc.JDBC4Connection@179bb86]
Returned connection 24755078 to pool.
15.2LOG4j
什么是log4j?
它是Apache的一个开源项目,通过使用log4j,我们可以控制日志信息输送的目的地是控制台、文件、GUI组件
我们也可以控制每一条日志的输出格式;
通过定义每一条日志信息的级别,我们能够更加细致地控制日志的生成过程。
通过一个配置文件来灵活地进行配置,而不需要修改应用的代码。
(1)先导入log4j的包
16、分页
思考:为什么要分页?
减少数据的处理量
16.1使用limit分页
select * from user limit startIndex,pageSize;
SELECT * FROM USER LIMIT 0,2;
使用mybatis实现分页,核心SQL
1、接口
//分页
List<User> getUserByLimit(Map<String,Integer> map);
2、Mapper.xml
<!--分页查询-->
<select id="getUserByLimit" parameterType="map" resultMap="UserMap">
select * from user limit #{startIndex},#{pageSize}
</select>
3、测试
@Test
public void getUserByLimit(){
SqlSession sqlSession = MybatisUtils.getSqlSession();
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
HashMap<String, Integer> map = new HashMap<>();
map.put("startIndex",0);
map.put("pageSize",2);
List<User> userList = mapper.getUserByLimit(map);
for (User user : userList) {
System.out.println(user);
}
sqlSession.close();
}
16.2RowBounds分页
17、使用注解开发
17.1注解在接口上实现
public interface UserMapper {
@Select("select * from user")
List<User> getUsers();
}
17.2需要在核心配置文件中绑定接口
<!--绑定接口-->
<mappers>
<mapper class="com.cs.dao.UserMapper"/>
</mappers>
17.3测试使用
本质:反射机制实现
底层:动态代理!
17.4CRUD
我们可以在工具类创建的时候实现自动提交事务
public static SqlSession getSqlSession(){
return sqlSessionFactory.openSession(true);
}
编写接口,增加注解
@Select("select * from user")
List<User> getUsers();
//方法存在多个参数,所有的参数前必须加上@Param("id")注解
@Select("select * from user where id = #{id}")
User getUserById(int id);
测试类
【注意:我们必须要将接口注册绑定到我们的核心配置文件中】
关于@Param()注解
基本类型的参数或者String类型,需要加上
引用类型不需要加
如果只有一个基本类型的话,可以忽略,但是建议都加上
在sql中引用的就是我们这里的@Param()中设定的属性名
18、Lombok
使用步骤:
(1)在IDEA中安装Lombok插件!
(2)在项目中导入lombok的jar包
@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
(3)
@Data
@AllArgsConstructor
@NoArgsConstructor
public class User {
private int id;
private String name;
private String password;
}
19、多对一处理
多个学生,对应一个老师
对于学生这边而言,关联…多个学生,关联一个老师【多对一】
对于老师而言,集合,一个老师有很多学生【一对多】
测试环境搭建
(1)导入lombok
(2)新建实体类Teacher,Student
(3)建立Mapper接口
(4)建立Mapper.xml
(5)在核心配置文件中绑定注册我们的Mapper接口或者文件【方式很多,随心挑】
(6)测试查询是否能够成功
按照查询嵌套处理
<mapper namespace="com.cs.dao.StudentMapper">
<!--
思路:1、查询所有的学生信息
2、根据查询出来的学生的tid,寻找对应的老师! 子查询
-->
<select id="getStudent" resultMap="StudentTeacher">
select * from student
</select>
<resultMap id="StudentTeacher" type="Student">
<result property="id" column="id"/>
<result property="name" column="name"/>
<!--复杂的属性需要单独处理
对象:association
集合:collection
-->
<association property="teacher" column="tid" javaType="Teacher"
select="getTeacher"/>
</resultMap>
<select id="getTeacher" resultType="Teacher">
select * from teacher where id = #{id}
</select>
</mapper>
按照结果嵌套处理
<mapper namespace="com.cs.dao.StudentMapper">
<!--按照结果嵌套处理-->
<select id="getStudent" 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多对一查询方式:
子查询
连表查询
20、一对多
比如:一个老师拥有多个学生
对于老师而言,就是一对多的关系
(1)环境搭建,和刚才一样
实体类
@Data
public class Student {
private int id;
private String name;
private int tid;
}
@Data
public class Teacher {
private int id;
private String name;
//一个老师拥有多个学生
private List<Student> students;
}
按照结果嵌套查询
<!--按结果嵌套查询-->
<select id="getTeacher" resultMap="TeacherStudent">
select s.id sid,s.name sname,t.name tname,t.id tid
from student s,teacher t
where s.tid = t.id and t.id = #{tid}
</select>
<resultMap id="TeacherStudent" type="Teacher">
<result property="id" column="tid"/>
<result property="name" column="tname"/>
<!--复杂的属性,我们需要单独处理 对象:association 集合:collection
javaType=“”指定属性的类型
集合中的泛型信息,使用ofType获取-->
<collection property="students" ofType="Student">
<result property="id" column="sid"/>
<result property="name" column="sname"/>
<result property="tid" column="tid"/>
</collection>
</resultMap>
按照查询嵌套查询
<select id="getTeacher2" resultMap="TeacherStudent2">
select * from 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>
小结
①关联-association【多对一】
②集合-collection【一对多】
③javaType & ofType
javaType用来指定实体类中属性的类型
ofType用来指定映射到List或者集合中的pojo类型,泛型中的约束类型!
注意点:
保证SQL的可读性,尽量保证通俗易懂
注意一对多和多对一中,属性名和字段的问题
如果问题不好排查错误,可以使用日志,建议使用LOG4J
21、动态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
创建一个基础工程
(1)导包
(2)编写配置文件
(3)编写实体类
@Data
public class Blog {
private int id;
private String title;
private String author;
private Date createTime;
private int views;
}
(4)编写实体类对应Mapper接口和Mapper.xml文件
<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>
<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层面,去执行一个逻辑代码
if
where set choose when
SQL片段
有的时候,我们会将一些功能的部分抽取出来,方便使用
(1)使用sql标签抽取公共部分
<sql id="if-title-author">
<if test="title != null">
and title = #{title}
</if>
<if test="author != null">
and author = #{author}
</if>
</sql>
(2)在需要使用的地方使用Include标签引用即可
<select id="queryBlogIF" parameterType="map" resultType="blog">
select * from blog
<where>
<include refid="if-title-author"></include>
</where>
</select>
注意事项:
最好基于单表来定义SQL片段!
不要存在where标签
动态SQL就是在拼接SQL语句,我们只要保证SQL的正确性,按照SQL的格式,去排列组合就可以了
建议:
先在Mysql中写出完整的SQL,再对应的去修改成为我们的动态SQL实现通用即可
面试高频
Mysql引擎
InnoDB底层原理
索引
索引优化
22、缓存
查询:连接数据库,耗资源
一次查询的结果,给他暂存在一个可以直接取到的地方->内存:缓存
一级缓存
一级缓存也叫本地缓存:SqlSession
与数据库同一次会话期间查询到的数据会放在本地缓存中
以后如果需要获取相同的数据,直接从缓存中拿,没必要再去查询数据库
测试步骤:
开启日志
测试在一个Session中查询两次记录
查看日志输出
Opening JDBC Connection
Created connection 9099067.
==> Preparing: select * from user where id = ?
==> Parameters: 1(Integer)
<== Columns: id, name, pwd
<== Row: 1, 狂神, 123456
<== Total: 1
User(id=1, name=狂神, pwd=123456)
User(id=1, name=狂神, pwd=123456)
true
缓存失效的情况
查询不同的东西
增删改操作,可能会改变原来的数据,所以必定会刷新缓存
查询不同的Mapper.xml
手动清理缓存
@Test
public void test(){
SqlSession sqlSession = MybatisUtils.getSqlSession();
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
User user = mapper.queryUsers(1);
System.out.println(user);
// mapper.updateUser(new User(2,"aaaa","bbbb"));
sqlSession.clearCache();//手动清理缓存
User user2 = mapper.queryUsers(1);
System.out.println(user2);
System.out.println(user==user2);
sqlSession.close();
}
小结:一级缓存默认是开启的,只在一次SqlSession中有效,也就是拿到连接到关闭连接这个区间段
一级缓存就是一个Map
二级缓存
步骤
(1)开启全局缓存
<!--显示开启全局缓存-->
<setting name="cacheEnabled" value="true"/>
(2)在要使用二级缓存的Mapper中开启
<!--在当前Mapper.xml中使用二级缓存-->
<cache eviction="FIFO" flushInterval="60000" size="512" readOnly="true"/>
(3)测试
问题:我们需要将实体类序列化!否则就会报错
小结:
只要开启了二级缓存,在同一个Mapper下就有效
所有的数据都会先放在一级缓存中
只有当会话提交,或者关闭的时候,才会提交到二级缓存中
自定义缓存-ehcache
Ehcache是一种广泛使用的开源Java分布式缓存,主要面向通用缓存
要在程序中使用ehcache,先要导包(不学)