Mybatis
简介
什么是MyBatis?
- MyBatis是一款持久层框架
- 它支持自定义 SQL、存储过程以及高级映射。
- MyBatis 避免了几乎所有的 JDBC 代码以及设置参数和获取结果集的工作。
- MyBatis 可以通过简单的 XML 或注解来配置和映射原始类型、接口和 Java POJO(Plain Old Java Objects,普通老式 Java 对象)为数据库中的记录。
- MyBatis本是apache的一个开源项目iBatis,2010年这个项目由apache software foundation迁移到了google,并且改名为MyBatis。
- 2013年11月迁移到Github。
持久层
完成持久化工作的代码块
持久化
- 数据持久化:将程序的数据在持久状态和瞬时状态转化的过程。
- 内存:断电即失
- JDBC持久化,io文件持久化
第一个mybatis程序
搭建数据库
CREATE DATABASE `mybatis`;
CREATE TABLE `user`(
`id` INT NOT NULL PRIMARY KEY,
`name` VARCHAR(30) DEFAULT NULL,
`pwd` VARCHAR(30) DEFAULT NULL
)ENGINE=INNODB DEFAULT CHARSET=utf8;
INSERT INTO `user`(`id`,`name`,`pwd`)VALUES
(1,"张三","123456"),
(4,"李四","123456"),
(3,"王五","123456"),
(2,"田七","123456");
搭建环境
-
新建一个普通的maven项目
-
删除src目录
-
导入maven依赖
<dependencies> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>4.11</version> <scope>test</scope> </dependency> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>8.0.30</version> </dependency> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis</artifactId> <version>3.5.11</version> </dependency> </dependencies>
新建一个新模块
编写mybatis核心配置文件
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration
PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"https://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="123456"/>
</dataSource>
</environment>
</environments>
</configuration>
编写mybatis工具类
package com.XZY_SUNSHINE.utils;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import java.io.IOException;
import java.io.InputStream;
public class MybatisUtils {
static {
try {
String resource = "org/mybatis/example/mybatis-config.xml";
InputStream inputStream = Resources.getResourceAsStream(resource);
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
} catch (IOException e) {
e.printStackTrace();
}
}
//既然有了 SqlSessionFactory,顾名思义,我们可以从中获得 SqlSession 的实例。
// SqlSession 提供了在数据库执行 SQL 命令所需的所有方法。
public static SqlSession get_SqlSession(){
return sqlSessionFactory.openSession();
}
}
编写代码
实体类
package com.XZY_SUNSHINE.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接口
package com.XZY_SUNSHINE.dao;
import com.XZY_SUNSHINE.pojo.User;
import java.util.List;
public interface UserDao {
List<User> getUserList();
}
接口实现类
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"https://mybatis.org/dtd/mybatis-3-mapper.dtd">
<!--namespace=绑定一个Dao/Mapper接口-->
<mapper namespace="com.XZY_SUNSHINE.dao.UserDao">
<!--select 查询语句-->
<select id="getUserList" resultType="com.XZY_SUNSHINE.pojo.User">
select * from mybatis.user
</select>
</mapper>
测试
package com.XZY_SUNSHINE.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;
//获取sqlSessionFactory对象
static {
try {
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 get_SqlSession(){
return sqlSessionFactory.openSession();
}
}
问题01
org.apache.ibatis.binding.BindingException: Type interface com.XZY_SUNSHINE.dao.UserDao is not known to the MapperRegistry.
解决
<!--每一个Mapper.xml文件都需要在mybatis核心配置文件中注册-->
<mappers>
<mapper resource="com/XZY_SUNSHINE/dao/UserMapper.xml"/>
</mappers>
问题02
Cause: org.apache.ibatis.builder.BuilderException: Error parsing SQL Mapper Configuration. Cause: java.io.IOException: Could not find resource com.XZY_SUNSHINE.dao/UserMapper.xml
解决
<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>
CRUD
- namespace:namespace中的包名要和Dao/Mapper接口的报名一致
- id:对应namespace中的方法名
- resulttype:SQL语句执行的返回值类型
- parameterType:传入参数的类型
select
Usermapper接口
//根据id查询用户
User getUserById(int id);
Usermapper.xml
<select id="getUserById" parameterType="int" resultType="com.XZY_SUNSHINE.pojo.User">
select * from mybatis.user where id=#{id}
</select>
测试
@Test
public void getUserById(){
//获取session对象
SqlSession sqlSession = MybatisUtils.get_SqlSession();
//绑定类
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
//执行查询语句
User user = mapper.getUserById(1);
//输出结果
System.out.println(user);
//关闭资源
sqlSession.close();
}
insert
Usermapper接口
//插入用户
int insertUser(User user);
Usermapper.xml
<insert id="insertUser" parameterType="com.XZY_SUNSHINE.pojo.User">
insert into mybatis.user(id,name,pwd) values(#{id},#{name},#{pwd})
</insert>
测试
@Test
public void insertUser(){
//获取session对象
SqlSession sqlSession = MybatisUtils.get_SqlSession();
//绑定类
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
//执行查询语句
User user1 = new User(7, "华航", "1234567");
mapper.insertUser(user1);
sqlSession.commit();
//关闭资源
sqlSession.close();
}
update
Usermapper接口
//更新用户的名字和密码
int updateUser(User user);
Usermapper.xml
<update id="updateUser" parameterType="com.XZY_SUNSHINE.pojo.User">
update mybatis.user set name=#{name},pwd=#{pwd} where id=#{id};
</update>
测试
@Test
public void updateUser(){
//获取session对象
SqlSession sqlSession = MybatisUtils.get_SqlSession();
//绑定类
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
//执行查询语句
User user1 = new User(7, "豪豪", "123456789");
mapper.updateUser(user1);
sqlSession.commit();
//关闭资源
sqlSession.close();
}
delete
Usermapper接口
//根据id删除用户
int deleteUserById(int id);
Usermapper.xml
<delete id="deleteUserById" parameterType="int">
delete from mybatis.user where id=#{id}
</delete>
测试
@Test
public void deleteUserById(){
//获取session对象
SqlSession sqlSession = MybatisUtils.get_SqlSession();
//绑定类
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
//执行查询语句
mapper.deleteUserById(7);
sqlSession.commit();
//关闭资源
sqlSession.close();
}
配置解析
核心配置文件
properties(属性)
settings(设置)
typeAliases(类型别名)
typeHandlers(类型处理器)
objectFactory(对象工厂)
plugins(插件)
environments(环境配置)
environment(环境变量)
transactionManager(事务管理器)
dataSource(数据源)
databaseIdProvider(数据库厂商标识)
mappers(映射器)
环境配置
可以配置多个环境,但每个 SqlSessionFactory 实例只能选择一种环境。
Mybatis默认的事务管理器就是JDBC,连接池:POOLED
属性
我们可以通过properties属性来实现引用配置文件
这些属性可以在外部进行配置,并可以进行动态替换。你既可以在典型的 Java 属性文件中配置这些属性,也可以在 properties 元素的子元素中设置。
编写一个配置文件
driver=com.mysql.jdbc.Driver
url=dbc:mysql://localhost:3306/mybatis?useSSL=true&useUnicode=true&characterEncoding=UTF-8
username=root
password=123456
在核心配置文件中引入
<properties resource="db.properties">
<property name="username" value="root"/>
<property name="pwd" value="123456"/>
</properties>
- 可以直接引入外部文件
- 可以在其中增加一些属性配置
- 如果两个文件有同一个字段,优先使用外部配置文件
类型别名
类型别名可为 Java 类型设置一个缩写名字。 它仅用于 XML 配置,意在降低冗余的全限定类名书写。
<typeAliases>
<typeAlias type="com.XZY_SUNSHINE.pojo.User" alias="User"/>
</typeAliases>
<select id="getUserList" resultType="User">
select * from mybatis.user
</select>
也可以指定一个包名,MyBatis 会在包名下面搜索需要的 Java Bean
扫描实体类的包,它的默认别名就为这个类的类名,首字母小写。
<typeAliases>
<package name="com.XZY_SUNSHINE.pojo"/>
</typeAliases>
在实体类比较少的时候,使用第一个方式
如果实体类十分多,建议使用第二种
第一种可以直接DIY别名,第二种可以通过注解的方式起别名
@Alias("author")
public class Author {
...
}
设置
这是 MyBatis 中极为重要的调整设置,它们会改变 MyBatis 的运行时行为。 下表描述了设置中各项设置的含义、默认值等。
映射器
方式一
<!-- 使用相对于类路径的资源引用 -->
<mappers>
<mapper resource="com/XZY_SUNSHINE/dao/UserMapper.xml"/>
</mappers>
方式二
<!-- 使用映射器接口实现类的完全限定类名 -->
<mappers>
<mapper class="com.XZY_SUNSHINE.dao.UserMapper"/>
</mappers>
注意点:
- 接口和它的mapper配置文件必须同名
- 接口和它的mapper配置文件必须在同一个包下
方式三
<!-- 将包内的映射器接口全部注册为映射器 -->
<mappers>
<package name="com.XZY_SUNSHINE.dao"/>
</mappers>
注意点:
- 接口和它的mapper配置文件必须同名
- 接口和它的mapper配置文件必须在同一个包下
生命周期和作用域
不同作用域和生命周期类别是至关重要的,因为错误的使用会导致非常严重的并发问题。
SqlSessionFactoryBuilder
- 一旦创建了 SqlSessionFactory,就不再需要它了。
- 最佳作用域是方法作用域(也就是局部方法变量)
SqlSessionFactory
- 可以想象为:数据库连接池
- 一旦被创建就应该在应用的运行期间一直存在,没有任何理由丢弃它或重新创建另一个实例。
- 最简单的就是使用单例模式或者静态单例模式
SqlSession
- 连接到连接池的一个请求
- SqlSession 的实例不是线程安全的,因此是不能被共享的,所以它的最佳的作用域是请求或方法作用域。
- 用完之后需要赶紧关闭,否则资源被占用
这里面每一个Mapper就代表一个具体的业务
解决属性名和字段名不一致的问题
public class User {
private int id;
private String name;
private String password;
查询结果
解决方法
方式一:起别名
<select id="getUserById" parameterType="int" resultType="user">
select id,name,pwd as password from mybatis.user where id=#{id}
</select>
方式二:resultMap
<resultMap id="UserMap" type="user">
<!--coloum为数据库表中的字段名称,property为类的属性 -->
<result column="pwd" property="password"/>
</resultMap>
<select id="getUserById" parameterType="int" resultMap="UserMap">
select * from mybatis.user where id=#{id}
</select>
- resultMap元素是 MyBatis 中最重要最强大的元素。
- ResultMap 的设计思想是,对简单的语句做到零配置,对于复杂一点的语句,只需要描述语句之间的关系就行了。
日志
日志工厂
如果一个数据库操作出现了异常,我们需要排错,日志就是最好的助手
- SLF4J
- LOG4J
- LOG4J2
- JDK_LOGGING
- COMMONS_LOGGING
- STDOUT_LOGGING
- NO_LOGGING
log4J
- Log4j是Apache的一个开源项目,通过使用Log4j,我们可以控制日志信息输送的目的地是控制台、文件
- 我们也可以控制每一条日志的输出格式;
- 通过定义每一条日志信息的级别,我们能够更加细致地控制日志的生成过程。
- 通过一个配置文件来灵活地进行配置,而不需要修改应用的代码。
<settings>
<setting name="logImpl" value="STDOUT_LOGGING"/>
</settings>
导入log4j
<!-- https://mvnrepository.com/artifact/log4j/log4j -->
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.17</version>
</dependency>
log4j的配置文件
### 配置根 ###
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 = %d{ABSOLUTE} %5p %c{1}:%L - %m%n
### 配置输出到文件 ###
log4j.appender.file = org.apache.log4j.FileAppender
log4j.appender.file.File = ./log/xzy.log
log4j.appender.file.Append = true
log4j.appender.file.Threshold = debug
log4j.appender.file.layout = org.apache.log4j.PatternLayout
log4j.appender.file.layout.ConversionPattern = %-d{yyyy-MM-dd HH:mm:ss} [ %t:%r ] - [ %p ] %m%n
### 设置输出sql的级别,其中logger后面的内容全部为jar包中所包含的包名 ###
log4j.logger.org.mybatis=debug
log4j.logger.java.sql=debug
log4j.logger.java.sql.Connection=debug
log4j.logger.java.sql.Statement=debug
log4j.logger.java.sql.PreparedStatement=debug
log4j.logger.java.sql.ResultSet=debug
配置log4j为日志的实现
<settings>
<setting name="logImpl" value="LOG4J"/>
</settings>
分页
语法
select * from table limit srartIndex,pageSize
limit分页
Mapper接口
//分页查询
List<User> getLimitList(Map<String ,Integer> map);
Mapperxml
<select id="getLimitList" parameterType="map" resultType="user">
select * from mybatis.user limit #{startIndex},#{pageSize}
</select>
Test
@Test
public void limitTest() {
//获取session对象
SqlSession sqlSession = MybatisUtils.get_SqlSession();
//绑定类
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
HashMap<String, Integer> map = new HashMap<String, Integer>();
map.put("startIndex",1);
map.put("pageSize",2);
//执行查询语句
List<User> list = mapper.getLimitList(map);
for (User user : list) {
System.out.println(user);
}
//关闭资源
sqlSession.close();
}
RowBounds分页查询
Mapper接口
//Rowbounds分页查询
List<User> getRowboundsList();
Mapper实现
<select id="getRowboundsList" resultMap="UserMap">
select * from mybatis.user
</select>
Test测试
@Test
public void RowboundsTest() {
//获取session对象
SqlSession sqlSession = MybatisUtils.get_SqlSession();
RowBounds bounds = new RowBounds(1,2);
List<User> list = sqlSession.selectList("com.XZY_SUNSHINE.dao.UserMapper.getRowboundsList", null, bounds);
//执行查询语句
for (User user : list) {
System.out.println(user);
}
//关闭资源
sqlSession.close();
}
使用注解开发
大家之前都学过面向对象编程,也学习过接口,但在真正的开发中,很多时候我们会选择面向接口编程
。根本原因∶解耦,可拓展,提高复用,分层开发中,上层不用管具体的实现,大家都遵守共同的标准,使得开发变得容易,规范性更好
在一个面向对象的系统中,系统的各种功能是由许许多多的不同对象协作完成的。在这种情况下,各个对象内部是如何实现自己的,对系统设计人员来讲就不那么重要了;
而各个对象之间的协作关系则成为系统设计的关键。小到不同类之间的通信,大到各模块之间的交互,在系统设计之初都是要着重考虑的,这也是系统设计的主要工作内容。面向接口编程就是指按照这种思想来编程。
关于接口的理解
- 接口从更深层次的理解,应是定义(规范,约束)与实现(名实分离的原则)的分离。
- 接口的本身反映了系统设计人员对系统的抽象理解。
- 接口应有两类:
- 第一类是对一个个体的抽象,它可对应为一个抽象体(abstract class);
- 第二类是对一个个体某一方面的抽象,即形成一个抽象面(interface) ;
- 一个体有可能有多个抽象面。抽象体与抽象面是有区别的。
三个面向区别
- 面向对象是指,我们考虑问题时,以对象为单位,考虑它的属性及方法.
- 面向过程是指,我们考虑问题时,以一个具体的流程(事务过程)为单位,考虑它的实现.
- 接口设计与非接口设计是针对复用技术而言的,与面向对象(过程)不是一个问题.更多的体现就是对系统整体的架构
使用注解开发
1.注解在接口上实现
@Select("select * from user")
List<User> getUserList();
2.核心配置绑定接口
<mappers>
<mapper class="com.XZY_SUNSHINE.dao.UserMapper"/>
</mappers>
本质:反射机制实现
底层:动态代理
CRUD
我们可以在工具类创建的时候实现自动提交事务
Mapper
//得到所有的用户
@Select("select * from user")
List<User> getUserList();
//根据id查询用户
@Select("select * from user where id=#{id}")
User getUserById(@Param("id") int id);
//插入用户
@Insert("insert into user(id,name,pwd) values(#{id},#{name},#{pwd})")
int insertUser(User user);
//更新用户的名字和密码
@Update("update user set name=#{name},pwd=#{pwd} where id=#{id}")
int updateUser(User user);
//根据id删除用户
@Delete("delete from user where id=#{id}")
int deleteUserById(@Param("id") int id);
Test
Test
public void UserTest(){
SqlSession sqlSession = MybatisUtils.get_SqlSession();
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
List<User> userList = mapper.getUserList();
for (User user : userList) {
System.out.println(user);
}
sqlSession.close();
}
@Test
public void getUserById(){
//获取session对象
SqlSession sqlSession = MybatisUtils.get_SqlSession();
//绑定类
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
//执行查询语句
User user = mapper.getUserById(1);
//输出结果
System.out.println(user);
//关闭资源
sqlSession.close();
}
@Test
public void insertUser(){
//获取session对象
SqlSession sqlSession = MybatisUtils.get_SqlSession();
//绑定类
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
//执行查询语句
User user1 = new User(7, "华航", "1234567");
mapper.insertUser(user1);
sqlSession.commit();
//关闭资源
sqlSession.close();
}
@Test
public void updateUser(){
//获取session对象
SqlSession sqlSession = MybatisUtils.get_SqlSession();
//绑定类
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
//执行查询语句
User user1 = new User(2, "豪豪", "123456789");
mapper.updateUser(user1);
sqlSession.commit();
//关闭资源
sqlSession.close();
}
@Test
public void deleteUserById(){
//获取session对象
SqlSession sqlSession = MybatisUtils.get_SqlSession();
//绑定类
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
//执行查询语句
mapper.deleteUserById(7);
sqlSession.commit();
//关闭资源
sqlSession.close();
}
关于@Param()注解
- 基本类型的参数或者String类型,需要加上
- 引用类型不需要加
- 如果只有一个基本类型的话,可以忽略,但是建议大家都加上
- 我们在SQL中引用的就是我们这里的@Param()中设定的属性名
#{},${}的区别
Lombok
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.
使用步骤
- 在IDEA安装Lombok插件
- 导入Lombok的jar包
@AllArgsConstructor@NoArgsConstructor:有参构造和无参构造
@Data:无参构造,get,set,tostring,hashcode,equals
多对一,一对多
测试环境搭建
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
@Data
public class Student {
private int id;
private String name;
private Teacher teacher;
}
@Data
public class Teacher {
private int id;
private String name;
}
Myabtis_config
<mappers>
<mapper class="com.XZY_SUNSHINE.dao.StudentMapper"/>
<mapper class="com.XZY_SUNSHINE.dao.TeacherMapper"/>
</mappers>
dao
public interface StudentMapper {
@Select("select * from student")
List<Student> getStudentList();
}
public interface TeacherMapper {
@Select("select * from teacher")
List<Teacher> geTeacherList();
}
多对一
- 多个学生,对应一个老师
- 对于学生这边而言,多个学生关联一个老师
- 对于老师而言,一个老师有很多学生【集合】
按照查询嵌套查询
<!--方式一:按照查询嵌套处理-->
<select id="getStudentList" resultMap="StudentTeacher" resultType="Student">
select * from mybatis.student
</select>
<resultMap id="StudentTeacher" type="Student">
<association property="teacher" column="tid" javaType="Teacher" select="getTeacher"/>
</resultMap>
<select id="getTeacher" resultType="Teacher">
select * from mybatis.teacher where id=#{tid}
</select>
按照结果嵌套查询
<!--方式二:按照结果嵌套查询-->
<select id="getStudentList" resultType="Student" resultMap="StudentTeacher">
select s.id sid,s.name sname,t.name tname,t.id tid
from student s,teacher t
where s.tid=t.id
</select>
<resultMap id="StudentTeacher" type="Student">
<result property="id" column="sid"/>
<result property="name" column="sname"/>
<association property="teacher" javaType="Teacher">
<result property="name" column="tname"/>
<result property="id" column="tid"/>
</association>
</resultMap>
一对多
按结果嵌套查询
<!--方式一:按照结果嵌套查询-->
<select id="geTeacherById" resultMap="TeacherStudent">
select t.id tid,t.name tname,s.id sid,s.name sname
from mybatis.student s,mybatis.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"/>
<collection property="students" ofType="Student">
<result property="id" column="sid"/>
<result property="name" column="sname"/>
<result property="tid" column="tid"/>
</collection>
</resultMap>
按查询嵌套查询
<!--方式二:按照查询嵌套查询-->
<select id="geTeacherById" resultMap="TeacherStudent">
select * from mybatis.teacher where id=#{tid}
</select>
<resultMap id="TeacherStudent" type="Teacher">
<result property="id" column="id"/>
<result property="name" column="name"/>
<collection property="students" javaType="ArrayList" ofType="Student" select="getStudent" column="id"/>
</resultMap>
<select id="getStudent" resultType="Student">
select * from mybatis.student where tid=#{id}
</select>
小结
- 关联 - association 【多对一】
- 集合 - collection 【一对多】
- javaType & ofType
- javaType用来指定实体类中属性的类型
- ofType用来指定映射到List或者集合中的pojo类型,泛型中的约束类型
注意点:
- 保证SQL的可读性,尽量保证通俗易懂
- 注意一对多和多对一中属性名和字段的问题
- 如果问题不好排查可以使用日志。
动态SQL
什么是动态SQL:动态SQL就是指根据不同的条件生成不同的SQL语句
如果你之前用过 JSTL 或任何基于类 XML 语言的文本处理器,你对动态 SQL 元素可能会感觉似曾相识。在 MyBatis 之前的版本中,需要花时间了解大量的元素。借助功能强大的基于 OGNL 的表达式,MyBatis 3 替换了之前的大部分元素,大大精简了元素种类,现在要学习的元素种类比原来的一半还要少。
if
choose (when, otherwise)
trim (where, set)
foreach
搭建环境
SQL环境搭建
CREATE TABLE `blog` (
`id` VARCHAR(30),
`title` VARCHAR(30) NOT NULL COMMENT '博客标题',
`author` VARCHAR(30) NOT NULL COMMENT '博客作者',
`create_time` DATETIME(0) NOT NULL COMMENT '创建时间',
`views` INT(30) NOT NULL COMMENT '浏览量',
PRIMARY KEY (`id`)
)
config.xml
<settings>
<setting name="logImpl" value="STDOUT_LOGGING"/>
<setting name="mapUnderscoreToCamelCase" value="true"/>
</settings>
<mappers>
<mapper class="com.XZY_SUNSHINE.dao.BlogMapper"/>
</mappers>
UuidUtils
public class UuidUtils {
public static String getUuid(){
return UUID.randomUUID().toString().substring(0,6).replaceAll("-","");
}
@Test
public void test(){
System.out.println(getUuid().getClass());
}
}
pojo.Blog
@Data
@AllArgsConstructor
@NoArgsConstructor
public class Blog {
private String id;
private String title;
private String author;
private Date createTime;
private int views;
}
blogMapper
public interface BlogMapper {
int insertBlog(Blog blog);
}
blogMapper.xml
<mapper namespace="com.XZY_SUNSHINE.dao.BlogMapper">
<insert id="insertBlog" parameterType="Blog">
insert into mybatis.blog(id, title, author, create_time, views) values(#{id},#{title},#{author},#{createTime},#{views})
</insert>
</mapper>
Test
@Test
public void Test(){
SqlSession sqlSession = MybatisUtils.get_SqlSession();
BlogMapper mapper = sqlSession.getMapper(BlogMapper.class);
String id= UuidUtils.getUuid();
Date date = new Date();
Blog blog=new Blog(UuidUtils.getUuid(),"Mybatis如此简单","SUNSHINE",date,2);
Blog blog1=new Blog(UuidUtils.getUuid(),"Spring如此简单","SUNSHINE",date,2);
Blog blog2=new Blog(UuidUtils.getUuid(),"SpringBoot如此简单","SUNSHINE",date,2);
System.out.println(blog);
mapper.insertBlog(blog);
mapper.insertBlog(blog1);
mapper.insertBlog(blog2);
sqlSession.close();
}
Where
where 元素只会在子元素返回任何内容的情况下才插入 “WHERE” 子句。而且,若子句的开头为 “AND” 或 “OR”,where 元素也会将它们去除。
IF
BlogMapper
List<Blog> queryBlogIf(Map map);
BlogMapper.xml
<select id="queryBlogIf" parameterType="map" resultType="blog">
select * from mybatis.blog
<where>
<if test="title != null">
title=#{title}
</if>
<if test="author != null">
and author=#{author}
</if>
</where>
</select>
Test
@Test
public void queryBlogIf(){
SqlSession sqlSession = MybatisUtils.get_SqlSession();
BlogMapper mapper = sqlSession.getMapper(BlogMapper.class);
HashMap<String, Object> map = new HashMap<String, Object>();
// map.put("title","Java如此简单");
map.put("author","SUNSHINE");
List<Blog> blogs = mapper.queryBlogIf(map);
for (Blog blog : blogs) {
System.out.println(blog);
}
}
Choose
blogMapper.xml
<select id="queryBlogChoose" parameterType="map" resultType="Blog">
select * from mybatis.blog
<where>
<choose>
<when test="author!=null">
author=#{author}
</when>
<when test="title!=null">
and title=#{title}
</when>
<when test="views!=null">
and views=#{views}
</when>
</choose>
</where>
</select>
Test
@Test
public void queryBlogIf(){
SqlSession sqlSession = MybatisUtils.get_SqlSession();
BlogMapper mapper = sqlSession.getMapper(BlogMapper.class);
HashMap<String, Object> map = new HashMap<String, Object>();
// map.put("title","Java如此简单");
map.put("author","SUNSHINE");
map.put("views",9999);
List<Blog> blogs = mapper.queryBlogChoose(map);
for (Blog blog : blogs) {
System.out.println(blog);
}
}
set
set 元素会动态地在行首插入 SET 关键字,并会删掉额外的逗号
blogMapper.xml
<update id="updateBlog" parameterType="map">
update mybatis.blog
<set>
<if test="author!=null">
author=#{author},
</if>
<if test="views!=null">
views=#{views}
</if>
</set>
where id=#{id}
</update>
Test
@Test
public void queryBlogIf(){
SqlSession sqlSession = MybatisUtils.get_SqlSession();
BlogMapper mapper = sqlSession.getMapper(BlogMapper.class);
HashMap<String, Object> map = new HashMap<String, Object>();
// map.put("title","Java如此简单");
map.put("author","XZY");
map.put("views",9999);
map.put("id","0e1584");
mapper.updateBlog(map);
}
sql片段
使用SQL标签抽取公共的部分
<sql id="updateIf">
<if test="author!=null">
author=#{author},
</if>
<if test="views!=null">
views=#{views}
</if>
</sql>
在需要引用的地方使用include标签引用即可
<update id="updateBlog" parameterType="map">
update mybatis.blog
<set>
<include refid="updateIf"></include>
</set>
where id=#{id}
</update>
foreach
Mapper.xml
<select id="queryBlogForeach" parameterType="map" resultType="Blog">
select * from mybatis.blog
<where>
<foreach collection="ids" open="id in(" separator="," close=")" item="item">
#{item}
</foreach>
</where>
</select>
Test
@Test
public void test(){
SqlSession sqlSession = MybatisUtils.get_SqlSession();
BlogMapper mapper = sqlSession.getMapper(BlogMapper.class);
HashMap<String, Object> map = new HashMap<String, Object>();
ArrayList<String> ids = new ArrayList<String>();
ids.add("314fbd");
ids.add("afbd60");
map.put("ids",ids);
List<Blog> blogs = mapper.queryBlogForeach(map);
for (Blog blog : blogs) {
System.out.println(blog);
}
sqlSession.close();
}
缓存
简介
连接数据库进行查询非常耗资源。我们可以将一次的查询结果暂存在一个可以直接取的地方->内存,内存存的东西就叫缓存
- 什么是缓存?
- 存在内存中的临时数据
- 将用户经常查询的数据放在缓存(内存)中,用户去查询数据就不用从磁盘上(关系型数据库数据文件)查询,从缓存中查询,从而提高查询效率,解决了高并发系统的性能问题
- 为什么使用缓存?
- 减少和数据库的交互次数,减少系统开销,提高系统效率
- 什么样的数据能使用缓存?
- 经常查询并且并且不经常改变的数据
Mybatis缓存
- Mybatis包含一个非常强大的查询缓存特性,他可以非常方便地定制和配置缓存。缓存可以极大地提升查询效率
- Mybatis系统中默认定义了两级缓存:一级缓存和二级缓存
- 默认情况下,只有一级缓存开启。(sqlsession级别的缓存:也称为本地缓存)
- 二级缓存需要手动开启和配置,它是基于namespace级别的缓存
- 为了提高扩展性,Mybatis定义了缓存接口Cache。我么可以通过实现Cache接口来定义二级缓存
一级缓存
一级缓存也叫本地缓存:
- 与数据库同一次会话期间查询到的数据会放在本地缓存中。
- 以后如果需要获取相同的数据,直接从缓存中拿,没必要去查询数据库
测试
缓存失效的情况
- 查询不同的东西
- 映射语句文件中的所有 insert、update 和 delete 语句会刷新缓存
- 查询不同的Mapper
- 手动清除缓存:sqlsession.clearcache()
二级缓存
- 二级缓存也叫全局缓存,一级缓存的作用域太低了,所以诞生了二级缓存
- 基于namespace级别的缓存,一个名称空间对应一个二级缓存
- 工作机制:
- 一个会话查询一条数据,这个数据就会被放在当前一级缓存中
- 如果当前会话关闭了,这个会话对应的一级缓存就没了,一级缓存中的会话数据就被保存到二级缓存中
- 新的会话查询信息,就可以从二级缓存中获取内容
步骤
1.开启缓存
2.在要使用缓存的Mapper中设置
3.将实体类进行序列化
缓存原理
自定义缓存-ehcache
Ehcache是一种广泛使用的开源java分布式缓存,主要通用缓存。
1.导包
<dependency>
<groupId>org.mybatis.caches</groupId>
<artifactId>mybatis-ehcache</artifactId>
<version>1.1.0</version>
</dependency>
2.在Mapper中指定缓存
<cache type="org.mybatis.caches.ehcache.EhcacheCache"/>
,用户去查询数据就不用从磁盘上(关系型数据库数据文件)查询,从缓存中查询,从而提高查询效率,解决了高并发系统的性能问题
2. 为什么使用缓存?
- 减少和数据库的交互次数,减少系统开销,提高系统效率
- 什么样的数据能使用缓存?
- 经常查询并且并且不经常改变的数据