Mybatis
1.简介
1.1什么是mybatis
前身:MyBatis 本是apache的一个开源项目iBatis
Mybatis特性:
- MyBatis 是一款优秀的持久层框架
- 它支持定制化 SQL、存储过程以及高级映射。
- MyBatis 避免了几乎所有的 JDBC 代码和手动设置参数以及获取结果集。
- MyBatis 可以使用简单的 XML 或注解来配置和映射原生类型、接口和 Java 的 POJO(Plain Old Java Objects,普通老式 Java 对象)为数据库中的记录。
1.2如何获得myabtis
1.maven仓库:
https://mvnrepository.com/artifact/org.mybatis/mybatis
2.GitHub上:
https://github.com/mybatis/mybatis-3
3.中文文档:
https://mybatis.org/mybatis-3/zh/index.html
1.3持久化
数据持久化:
- 持久化就是将程序的数据在持久状态和瞬时状态转化的过程
- 内存:断电即失
- 持久化的方式:数据库(jdbc)、io文件持久化
为什么需要持久化?
- 内存太贵了
- 有一些数据不能丢失,比如银行的存款
1.4持久层
- 完成持久化工作的代码块
- 层界限十分明显
Dao层、Service层、Controller层
2.第一个MyBatis程序
分析:搭建环境---->导入Mybatis---->编写代码---->测试
2.1搭建环境
2.1.1搭建数据库
CREATE DATABASE `mybatis`
USE `mybatis`
CREATE TABLE `user`(
`id` INT(10) NOT NULL PRIMARY KEY,
`name` VARCHAR(20) NOT NULL ,
`pwd` VARCHAR(20) NOT NULL
)ENGINE=INNODB DEFAULT CHARSET=utf8;
INSERT INTO `user` (id, `name`, `pwd`)
VALUES (1,'张三','123456789'),
(2,'李四','123456789'),
(3,'王五','123456789')
2.1.2新建maven项目
- 新建一个普通的maven项目
- 删除src目录
- 导入maven依赖
- mybatis
- mysql
- junit
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.mahui</groupId>
<artifactId>mybatis-study</artifactId>
<packaging>pom</packaging>
<version>1.0-SNAPSHOT</version>
<modules>
<module>mybatis-01</module>
</modules>
<dependencies>
<!-- https://mvnrepository.com/artifact/org.mybatis/mybatis -->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.5.6</version>
</dependency>
<!-- https://mvnrepository.com/artifact/mysql/mysql-connector-java -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.47</version>
</dependency>
<!-- https://mvnrepository.com/artifact/junit/junit -->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.13.1</version>
<scope>test</scope>
</dependency>
</dependencies>
</project>
2.2创建一个新的模块
2.2.1 编写Mybatis核心配置文件
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">
<!--mybatis核心配置文件-->
<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=utf8"/>
<property name="username" value="root"/>
<property name="password" value="123456"/>
</dataSource>
</environment>
</environments>
<!--注册mapper-->
<mappers>
<mapper resource="com\mahui\dao\User\UserMapper.xml"/>
</mappers>
</configuration>
2.2.2编写Mybatis工具类
package com.mahui.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 MybatisUtil {
//sqlSessionFactory --> sqlSession
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编写代码
2.3.1实体类
package com.mahui.pojo;
import java.lang.String;
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 + '\'' +
'}';
}
}
2.3.2Dao接口
UserMapper.java
package com.mahui.dao.User;
import com.mahui.pojo.User;
import java.util.List;
public interface UserMapper {
//获得用户列表
List<User> getUserList();
}
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">
<!--namespace:绑定一个对应的mapper或dao-->
<mapper namespace="com.mahui.dao.User.UserMapper">
<!--select 查询语句-->
<select id="getUserList" resultType="com.mahui.pojo.User">
select * from `user`
</select>
</mapper>
2.4测试
package com.mahui.dao.User;
import com.mahui.pojo.User;
import com.mahui.utils.MybatisUtil;
import org.apache.ibatis.session.SqlSession;
import org.junit.Test;
import java.util.List;
public class UserTest {
@Test
public void UserMapperTest(){
//通过工具类获得sqlsession
SqlSession sqlSession = MybatisUtil.getsqlSession();
//通过sqlsession获得mapper
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
//运行方法
List<User> userList = mapper.getUserList();
for (User user : userList) {
System.out.println(user);
}
//关闭资源
sqlSession.close();
}
}
2.5遇到的问题
2.5.1 没有注册mapper
错误信息:org.apache.ibatis.binding.BindingException: Type interface com.kuang.dao.UserDao is not known to the MapperRegistry.
在mybatis-config.xml中注册mapper
2.5.2资源过滤问题
java.io.IOException: Could not find resource com\mahui\dao\User\UserMapper.xml
找不到UserMapper.xml这是maven的原因,约定大于配置。
所以在pom.xml中配置
<!--在build中配置resources,来防止我们资源导出失败的问题-->
<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.6官方文档对使用到的三个类解释
3.CRUD
1.namespace
命名空间:包名必须要跟Dao/Mapper接口的包名一致!
2.select
选择查询语句:
- id:就是对应的namespace中的方法名
- resultType:Sql语句执行的返回值
- parameterType:参数类型
1.编写接口
//根据id查询用户
User getUserByid(int id);
2.编写对应的mapper中的sql语句
<select id="getUserByid" parameterType="int" resultType="com.mahui.pojo.User">
select * from mybatis.user where id = #{id}
</select>
3.测试
public void getUserByidTest(){
SqlSession session = MybatisUtil.getsqlSession();
UserMapper mapper = session.getMapper(UserMapper.class);
User user = mapper.getUserByid(1);
System.out.println(user);
session.close();
}
3.insert
1.编写接口
//插入用户
int insertUser(User user);
2.编写对应的mapper中的sql语句
<insert id="insertUser" parameterType="com.mahui.pojo.User">
insert into mybatis.user(id,name,pwd) values (#{id},#{name},#{pwd})
</insert>
3.测试
public void insertUserTest(){
SqlSession session = MybatisUtil.getsqlSession();
UserMapper mapper = session.getMapper(UserMapper.class);
int i = mapper.insertUser(new User(4, "王五", "454554"));
//提交事务
session.commit();
//关闭资源
session.close();
}
4.update
1.编写接口
//修改用户
int updateUserById(User user);
2.编写对应的mapper中的sql语句
<update id="updateUserById" parameterType="com.mahui.pojo.User">
update mybatis.user set name=#{name},pwd=#{pwd} where id=#{id}
</update>
3.测试
public void updateUser(){
SqlSession session = MybatisUtil.getsqlSession();
UserMapper mapper = session.getMapper(UserMapper.class);
int i = mapper.updateUserById(new User(4, "修改", "asdf"));
//提交事务
session.commit();
//关闭资源
session.close();
}
5.delete
1.编写接口
//根据id删除用户
int deleteUser(int id);
2.编写对应的mapper中的sql语句
<delete id="deleteUser" parameterType="int">
delete from mybatis.user where id=#{id}
</delete>
3.测试
public void deleteUser(){
SqlSession session = MybatisUtil.getsqlSession();
UserMapper mapper = session.getMapper(UserMapper.class);
int i = mapper.deleteUser(4);
//提交事务
session.commit();
//关闭资源
session.close();
}
注意:
- 增删改需要提交事务!
- 增删改不用写返回值,但是查询必须写结果集类型
6.错误分析
idea排查错误应该从下往上排查错误!
- 标签不要匹配错
- resource绑定mapper需要使用路径
- 程序的配置文件必须符合规范
- NullPointerException,没有注册到资源
- maven资源没有导出问题,加上资源过滤
7.Map
如果我们的实体类的参数过多,或者数据库中的表,字段或者参数过多,使用map传递参数
1.编写接口
//通过map传递参数插入用户
int insertUser2(Map map);
2.编写对应的mapper中的sql语句
<insert id="insertUser2" parameterType="map">
insert into mybatis.user(id,name,pwd) values (#{userid},#{username},#{userpwd})
</insert>
3.测试
public void inserUserTest2(){
SqlSession session = MybatisUtil.getsqlSession();
UserMapper mapper = session.getMapper(UserMapper.class);
Map map = new HashMap<String, Object>();
map.put("userid",4);
map.put("username","李五");
map.put("userpwd","1234556");
mapper.insertUser2(map);
//提交事务
session.commit();
//关闭资源
session.close();
}
map传递的参数,直接在sql中取出key即可! parameterType=“map”
对象传递参数,直接在sql中取出对象的属性即可 parameterType=“Objecct”
只有一个基本参数的情况下,直接在sql中取到,有多个参数的情况下使用map或者注解
8.模糊查询
1.编写接口
//模糊查询
List<User> getUserList2(String name);
2.编写对应的mapper中的sql语句
<select id="getUserList2" resultType="com.mahui.pojo.User">
select *from mybatis.user where name like #{value}
</select>
3.测试
public void getUserList(){
SqlSession session = MybatisUtil.getsqlSession();
UserMapper mapper = session.getMapper(UserMapper.class);
List<User> userList = mapper.getUserList2("%李%");
for (User user : userList) {
System.out.println(user);
}
session.commit();
session.close();
}
1.Java代码执行的时候,传递通配符%%
List<User> userList = mapper.getUserList2("%李%");
2.在sql拼接中使用通配符!
select *from mybatis.user where name like "%"#{value}"%"
4.配置解析
1.核心配置文件
- mybatis-config.xml
- Mybatis的配置文件包含了mybatis的设置和属性信息
configuration(配置)
properties(属性)
settings(设置)
typeAliases(类型别名)
typeHandlers(类型处理器)
objectFactory(对象工厂)
plugins(插件)
environments(环境配置)
environment(环境变量)
transactionManager(事务管理器)
dataSource(数据源)
databaseIdProvider(数据库厂商标识)
mappers(映射器)
2.环境配置(environments)
mybatis可以配置多套环境,但是,每个sqlSessionFactory实例只能选择一种环境。
mybatis的事务管理器有两种:
-
JDBC
-
MANAGED
mybaitis的连接池:
- UNPOOLED
- POOLED
- JNDI
mybatis默认的事务管理器就是JDBC,连接池:POOLED
3.属性(properties)
我们可以使用properties属性来实现引用配置文件。
这些属性都是可以外部配置且可以动态替换的,既可以在典型的Java属性文件中配置,也可以通过properties元素的子元素来传递[db.properties]
-
编写一个配置文件
driver=com.mysql.jdbc.Driver url=jdbc:mysql://localhost:3306/mybatis?useSSL=true&useUnicode=true&characterEncoding=utf8 username=root password=123456
-
在核心配置文件中引入
<properties resource="db.properties" > <property name="key" value="value"/> </properties>
properties:
- 可以直接引入外部文件
- 可以在其中增加一些属性配置
- 如果两个文件有同一个字段,优先使用外部配置文件的
4.别名(typeAliases)
- 类型别名可为 Java 类型设置一个缩写名字
- 意在降低冗余的全限定类名书写
分为两种方式:
1.typeAlias 直接给实体类起别名
<typeAliases>
<typeAlias type="com.mahui.pojo.User" alias="User"/>
</typeAliases>
2.package 扫描实体类包
扫描实体类的包,它的默认别名是这个类的类名,首字母小写,但是大写也可以查出来!
<typeAliases>
<package name="com.mahui.pojo"/>
</typeAliases>
在实体类比较少的时候,推荐使用第一种方式
在实体类十分多的时候,推荐使用第二种方式
第一种可以随意的给类起别名,但是第二种不行,如果需要改,则需要在实体类上增加注解
@Alias("user")
public class User {}
5.设置(settings)
MyBatis 中极为重要的调整设置,它们会改变 MyBatis 的运行时行为
中文文档中描述了各项设置的含义和默认值:https://mybatis.org/mybatis-3/zh/configuration.html
设置日志:
6.映射器
MapperRegistry:注册绑定我们的Mapper文件
1.使用resource注册(t推荐)
<mappers>
<!--每一个mapper.xml都需要在mybatis核心文件中配置-->
<mapper resource="com\mahui\dao\User\UserMapper.xml"/>
</mappers>
2.使用class文件绑定注册
<mappers>
<mapper class="com.mahui.dao.User.UserMapper"/>
</mappers>
注意点:
- 接口和它的mapper配置文件必须同名
- 接口和它的mapper配置文件必须在同一个包下
3.使用扫描包进行注册绑定
<mappers>
<package name="com.mahui.dao"/>
</mappers>
注意点:
- 接口和它的mapper配置文件必须同名
- 接口和它的mapper配置文件必须在同一个包下
7.生命周期和作用域
不同作用域和生命周期类别是至关重要的,因为错误的使用会导致非常严重的并发问题。
1.SqlSessionFactoryBuilder
- 一旦创建SqlSessionFactory,就不再需要它了
- 局部变量
2.SqlSessionFactory
- 可以理解为:数据库连接池
- SqlSessionFactory一旦被创建就应该在应用的运行期间一直存在,没有任何理由丢弃或者创建另一个新的实例
- SqlSessionFactory的最佳作用域是应用作用域
- 最简单的就是使用单例模式或者静态单例模式
3.SqlSession
- 连接到连接池的一个请求
- SqlSession的实例不是线程安全的,所以不能被共享。
- 所以它的最佳作用域是请求或者方法作用域
- 用完之后立即关闭,否则资源被占用。
5.解决属性名和字段名不一致的问题
1.出现的问题
数据库中的字段跟实体类中的属性名不一致的情况,测试出现问题,找不到不一致的值
查询结果:
解决方法:
-
起别名
<select id="getUserByid" parameterType="int" resultType="com.mahui.pojo.User"> select id,name,pwd as password from mybatis.user where id = #{id} </select>
2.resultMap
结果集映射:
<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 mybatis.user where id = #{id}
</select>
6.日志
6.1 日志工厂
如果数据库操作,出现了异常,我们需要使用日志排错。
过去:sout 、debug
现在:日志工厂!
- SLF4J
- LOG4J 【掌握】
- LOG4J2
- JDK_LOGGING
- COMMONS_LOGGING
- STDOUT_LOGGING 【不需要配置,标准日志输出】
- NO_LOGGING
在mybatis核心配置文件中,配置我们的日志!
<settings>
<setting name="logImpl" value="STDOUT_LOGGING"/>
</settings>
6.2 Log4j
什么是Log4j?
- Log4j是Apache的一个开源项目,通过使用Log4j,我们可以控制日志信息输送的目的地是控制台、文件、GUI组件
- 我们也可以控制每一条日志的输出格式;
- 通过定义每一条日志信息的级别,我们能够更加细致地控制日志的生成过程。
- 通过一个配置文件来灵活地进行配置,而不需要修改应用的代码。
1.导入log4j的包
<!-- https://mvnrepository.com/artifact/log4j/log4j -->
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.17</version>
</dependency>
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/ma.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="LOG4J"/>
</settings>
4.log4j的使用。直接测试运行刚才的查询
6.3简单的使用
1.在使用Log4j的类中,导入包
import org.apache.log4j.Logger;
2.日志对象,参数为当前类的class
static Logger logger = Logger.getLogger(userTest.class);
3.日志级别
logger.info("info:进入了testLog4j");
logger.debug("debug:进入了testLog4j");
logger.error("error:进入了testLog4j");
7.分页
7.1 使用limit分页
sql语法:
select * from mybatis.user limit startIndex,pageSize;
使用mybatis实现分页,核心sql
1.接口
//分页
List<User> getUserList(Map<String,Object> map);
2.mapper.xml
<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="getUserList" resultMap="UserMap" parameterType="map">
select * from mybatis.user limit #{startIndex},${pageSize};
</select>
3.测试
@Test
public void UserlimitTest() {
SqlSession session = MybatisUtil.getsqlSession();
UserMapper mapper = session.getMapper(UserMapper.class);
HashMap<String, Object> map = new HashMap<String, Object>();
map.put("startIndex",1);
map.put("pageSize",2);
List<User> users = mapper.getUserList(map);
for (User user : users) {
System.out.println(user);
}
session.close();
}
7.2RowBounds分页
不再使用sql实现分页,通过java层面实现分页
1.接口
//rowbounds
List<User> getUserListByRowBounds();
2.mapper.xml
<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="getUserListByRowBounds" resultMap="UserMap" parameterType="map">
select * from mybatis.user
</select>
3.测试
@Test
public void UserrowboundsTest() {
SqlSession session = MybatisUtil.getsqlSession();
// 通过java层面实现分页
List<User> users = session.selectList("com.mahui.dao.User.UserMapper.getUserListByRowBounds", null, new RowBounds(0, 2));
for (User user : users) {
System.out.println(user);
}
session.close();
}
7.3mybatis的分页插件
了解即可:
8.注解开发
8.1面向接口编程
- 大家之前都学过面向对象编程,也学习过接口,但在真正的开发中,很多时候我们会选择面向接口编程
- 根本原因 : 解耦 , 可拓展 , 提高复用 , 分层开发中 , 上层不用管具体的实现 , 大家都遵守共同的标准 , 使得开发变得容易 , 规范性更好
- 在一个面向对象的系统中,系统的各种功能是由许许多多的不同对象协作完成的。在这种情况下,各个对象内部是如何实现自己的,对系统设计人员来讲就不那么重要了;
- 而各个对象之间的协作关系则成为系统设计的关键。小到不同类之间的通信,大到各模块之间的交互,在系统设计之初都是要着重考虑的,这也是系统设计的主要工作内容。面向接口编程就是指按照这种思想来编程。
关于接口的理解
- 接口从更深层次的理解,应是定义(规范,约束)与实现(名实分离的原则)的分离。
- 接口的本身反映了系统设计人员对系统的抽象理解。
- 接口应有两类:
- 第一类是对一个个体的抽象,它可对应为一个抽象体(abstract class);
- 第二类是对一个个体某一方面的抽象,即形成一个抽象面(interface);
- 一个体有可能有多个抽象面。抽象体与抽象面是有区别的。
三个面向区别
- 面向对象是指,我们考虑问题时,以对象为单位,考虑它的属性及方法 .
- 面向过程是指,我们考虑问题时,以一个具体的流程(事务过程)为单位,考虑它的实现 .
- 接口设计与非接口设计是针对复用技术而言的,与面向对象(过程)不是一个问题.更多的体现就是对系统整体的架构
8.2使用注解开发
1.编写接口,将sql写在注解上
@Select("select * from user")
List<User> getUser();
2.在核心配置文件中绑定接口
<mappers>
<mapper class="com.mahui.dao.User.UserMapper"/>
</mappers>
3.测试
@Test
public void getUsers(){
SqlSession session = MybatisUtil.getsqlSession();
UserMapper mapper = session.getMapper(UserMapper.class);
List<User> users = mapper.getUser();
for (User user : users) {
System.out.println(user);
}
session.close();
}
4.测试出现问题
实体类的属性跟数据库的列不对应,简单查询可以使用注解,复杂一点的还是使用xml配置
4.探究本质
本质:反射机制实现
底层:动态代理!
打断点进行分析:
所有的mybatis-config.xml信息都在session中
9.拿到类的所有信息
8.3CRUD
1.查询
1.编写接口
//查询
@Select("select * from user where id=#{id}")
User getUserByid(@Param("id")int id);
2.测试
@Test
public void getUserByid(){
SqlSession session = MybatisUtil.getsqlSession();
UserMapper mapper = session.getMapper(UserMapper.class);
User userByid = mapper.getUserByid(1);
System.out.println(userByid);
session.close();
}
2.增加
1.编写接口
//增加
@Insert("insert into user(id,name,pwd) values (#{id},#{name},#{password})")
int addUser(User user);
2.测试
@Test
public void addUser(){
SqlSession session = MybatisUtil.getsqlSession();
UserMapper mapper = session.getMapper(UserMapper.class);
int i = mapper.addUser(new User(5, "李明", "123456"));
//提交事务
session.commit();
session.close();
}
3.更新
1.编写接口
//修改
@Update("update user set name=#{name},pwd=#{password} where id=#{id}")
int updateUser(User user);
2.测试
@Test
public void updateUser(){
SqlSession session = MybatisUtil.getsqlSession();
UserMapper mapper = session.getMapper(UserMapper.class);
int i = mapper.updateUser(new User(5, "李华", "654321"));
session.commit();
session.close();
}
4.删除
1.编写接口
//删除
@Delete("delete from user where id=#{id}")
int deleteUser(@Param("id") int id);
2.测试
@Test
public void deleteUser(){
SqlSession session = MybatisUtil.getsqlSession();
UserMapper mapper = session.getMapper(UserMapper.class);
int i = mapper.deleteUser(1);
session.commit();
session.close();
}
**注意:**我们必须要将接口注册绑定到我们的和新配置文件中
8.4@Param()注解
- 基本类型的参数或者String类型需要加上
- 引用类型不需要加上
- 如果只有一个基本类型的话,可以忽略,但是建议加上
- 我们的sql中引用的是@param()中设定的属性名!必须sql与@param一致
8.5#{}与${}区别:
#{}:可以防止sql注入
${}: 不可以防止sql注入
9.mybatis的详细执行流程!
10.lombok使用
1.在idea上安装lombok插件
2.导入依赖
<!-- https://mvnrepository.com/artifact/org.projectlombok/lombok -->
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.18.16</version>
<scope>provided</scope>
</dependency>
3.创建实体类
在实体类上加注解
@Data
@AllArgsConstructor 有全部参数的构造器
@NoArgsConstructor 无参构造
lombok中的注解:
@Getter and @Setter
@FieldNameConstants
@ToString
@EqualsAndHashCode
@AllArgsConstructor, @RequiredArgsConstructor and @NoArgsConstructor
@Log, @Log4j, @Log4j2, @Slf4j, @XSlf4j, @CommonsLog, @JBossLog, @Flogger
@Data :无参构造,get,set,tostring,hashcode,equals
@Builder
@Singular
@Delegate
@Value
@Accessors
@Wither
@SneakyThrows
11.多对一处理
环境搭建:
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');
pojo类
student
@Data
@AllArgsConstructor
@NoArgsConstructor
public class Student {
private int id;
private String name;
private Teacher teacher;
}
teacher
@Data
@AllArgsConstructor
@NoArgsConstructor
public class Teacher {
private int id;
private String name;
}
多对一:
以老师和学生为例:多个学生,一个老师
- 对于学生这边而言,关联 多个学生对一个老师【多对一】
- 对于老师这边而言,集合 一个老师对应多个学生【一对多】
查询接口
// 查询学生的信息
List<Student> getStudent();
11.1按照查询嵌套处理
<select id="getStudent" resultMap="getStudentMap">
select * from mybatis.student
</select>
<!--collection 集合-->
<!--association 对象-->
<resultMap id="getStudentMap" type="Student">
<result property="id" column="id"/>
<result property="name" column="name"/>
<association property="teacher" javaType="Teacher" column="tid" select="getTeacher"/>
</resultMap>
<select id="getTeacher" resultType="Teacher">
select * from mybatis.teacher where id=#{tid}
</select>
11.2按照结果嵌套处理
<select id="getStudent" resultMap="getStudentMap">
select s.id sid,s.name sname,t.name tname from student s,teacher t where s.tid =t.id
</select>
<resultMap id="getStudentMap" type="Student">
<result property="id" column="sid"/>
<result property="name" column="sname"/>
<association property="teacher" javaType="Teacher">
<result property="name" column="tname"/>
</association>
</resultMap>
12.一对多处理
环境搭建
实体类:
student:
@Data
@AllArgsConstructor
@NoArgsConstructor
public class Student {
private int id;
private String name;
private int tid;
}
teacher:
@Data
@AllArgsConstructor
@NoArgsConstructor
public class Teacher {
private int id;
private String name;
private List<Student> students;
}
12.1按照查询嵌套处理
<select id="getTeacherByid" resultMap="getTeacherStudent">
select * from mybatis.teacher where id=#{tid}
</select>
<resultMap id="getTeacherStudent" type="Teacher">
<result column="id" property="id"/>
<result column="name" property="name"/>
<!--column将id传给下一个查询语句-->
<collection property="students" javaType="ArrayList" ofType="Student" select="getStudent" column="id"/>
</resultMap>
<select id="getStudent" resultType="Student">
select * from mybatis.student where tid=#{tid}
</select>
12.2按照结果嵌套处理
<select id="getTeacherByid" resultMap="getTeacherStudent">
select s.id sid,s.name sname,t.name tname, t.id tid from teacher t ,student s where s.tid=t.id and t.id=#{tid};
</select>
<resultMap id="getTeacherStudent" type="Teacher">
<result property="id" column="tid"/>
<result property="name" column="tname"/>
<!--ofType 集合泛型中的类型-->
<collection property="students" ofType="Student">
<result property="id" column="sid"/>
<result property="name" column="sname"/>
<result property="tid" column="tid"/>
</collection>
</resultMap>
总结:
- 关联:association 多对一
- 集合:collection 一对多
- javaType 用来指定实体类中属性的类型
- ofType 用来指定映射到List或者集合中的pojo类型 泛型中的约束类型!
13.动态sql
什么是动态sql?
动态SQL就是指根据不同的条件生成不同的SQL语句,本质还是sql语句,只是我们可以在sql层面去执行一个逻辑代码。动态sql就是在拼接sql,我们要保证sql的正确性,按照sql的格式排列组合就行。
- 建议:先在mysql中写出完整的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
pojo:
@Data
@AllArgsConstructor
@NoArgsConstructor
public class Blog {
private int id;
private String title;
private String author;
private Date createtime;
private int views;
}
13.1使用if
<select id="getBlog" 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>
13.2choose(when,otherwise)
<select id="queryBlog" resultType="blog" parameterType="map">
select * from mybatis.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>
13.2trim(where,set)
<update id="updateBlog" parameterType="map" >
update mybatis.blog
<set>
<if test="title!=null">
title=#{title},
</if>
<if test="author!=null">
author=#{author},
</if>
</set>
where id=#{id}
</update>
13.3sql片段
<sql id="if-title-author">
<if test="title!=null">
and title=#{title}
</if>
<if test="author!=null">
and author=#{author}
</if>
</sql>
<!--使用sql将重复的sql语句写入,通过include标签引用-->
<select id="getBlog" resultType="Blog" parameterType="map">
select * from mybatis.blog where 1=1
<include refid="if-title-author"/>
</select>
13.4Foreach
<!--select * from mybatis.blog where id=1 or id=2 or id=3-->
<select id="queryBlogByid" parameterType="map" resultType="blog">
select * from mybatis.blog
<where>
<foreach collection="ids" open="" close="" separator="or" item="id">
id=#{id}
</foreach>
</where>
</select>
14缓存
查询需要连接数据库,耗费资源,一次查询结果,给他暂存在一个可以直接渠道的地方!—> 内存:缓存
下次再查同样的数据的时候,就不去数据库中查找,去缓存中查。
14.1.简介
-
什么是缓存 [ Cache ]?
- 存在内存中的临时数据。
- 将用户经常查询的数据放在缓存(内存)中,用户去查询数据就不用从磁盘上(关系型数据库数据文件)查询,从缓存中查询,从而提高查询效率,解决了高并发系统的性能问题。
-
为什么使用缓存?
- 减少和数据库的交互次数,减少系统开销,提高系统效率。
-
什么样的数据能使用缓存?
- 经常查询并且不经常改变的数据。【可以使用缓存】
14.2.Mybatis缓存
- MyBatis包含一个非常强大的查询缓存特性,它可以非常方便地定制和配置缓存。缓存可以极大的提升查询效率。
- MyBatis系统中默认定义了两级缓存:一级缓存和二级缓存
-
默认情况下,只有一级缓存开启。(SqlSession级别的缓存,也称为本地缓存)
-
二级缓存需要手动开启和配置,他是基于namespace级别的缓存。
-
为了提高扩展性,MyBatis定义了缓存接口Cache。我们可以通过实现Cache接口来自定义二级缓存
-
14.3.一级缓存
- 一级缓存也叫本地缓存: SqlSession
- 与数据库同一次会话期间查询到的数据会放在本地缓存中。
- 以后如果需要获取相同的数据,直接从缓存中拿,没必须再去查询数据库;
测试:
1.开启日志
2.测试在一个session中查询两次相同的记录
3.查看日志输出
缓存失效的情况:
1.查询不同的东西
2.增删改操作,可能会改变原来的数据,所以必定会刷新缓存1
3.查询不同的mapper.xml
4.手动清理缓存
小结:一级缓存默认是开启的,只在一次SqlSession中有效,也就是拿到连接到关闭连接这个区间段!
一级缓存就是一个Map。
14.4.二级缓存
- 二级缓存也叫全局缓存,一级缓存作用域太低了,所以诞生了二级缓存
- 基于namespace级别的缓存,一个名称空间,对应一个二级缓存;
- 工作机制
- 一个会话查询一条数据,这个数据就会被放在当前会话的一级缓存中;
- 如果当前会话关闭了,这个会话对应的一级缓存就没了;但是我们想要的是,会话关闭了,一级缓存中的数据被保存到二级缓存中;
- 新的会话查询信息,就可以从二级缓存中获取内容;
- 不同的mapper查出的数据会放在自己对应的缓存(map)中;
步骤:
1.开启设置
<!--开启缓存设置显示的开启全局缓存-->
<setting name="cacheEnabled" value="true"/>
2.在mapper.xm文件开启缓存
<!--在mapper.xml中使用二级缓存-->
<cache/>
可以自定义设置参数
3.测试
1.问题:我们需要将实体类序列化!否则就会报错!
Caused by: java.io.NotSerializableException: com.kuang.pojo.User
14.5.缓存原理
14.6.自定义缓存ehcache
Ehcache是一种广泛使用的开源Java分布式缓存。主要面向通用缓存
1.导入ehcache依赖
<!-- https://mvnrepository.com/artifact/org.mybatis.caches/mybatis-ehcache -->
<dependency>
<groupId>org.mybatis.caches</groupId>
<artifactId>mybatis-ehcache</artifactId>
<version>1.1.0</version>
</dependency>
2.在mapper中指定使用我们的ehcache缓存实现
<!--在当前Mapper.xml中使用二级缓存-->
<cache type="org.mybatis.caches.ehcache.EhcacheCache"/>
3.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>