文章目录
- MyBatis
- 1、MyBatis 的优势
- 2、MyBatis 的缺点
- 3、MyBatis 的使用
- 4、使用 Maven 搭建 MyBatis 项目
- 5、使用 MyBatis 的注意事项
- 6、自定义接口
- 7、MyBatis 底层实现
- 8、parameterType
- 9、resultType
- 10、多表关联查询
- 11、MyBatis 延迟加载
- 12、MyBatis 缓存
- 12.1、一级缓存
- 12.2、二级缓存
- 12.3、总结
- 13、MyBatis 动态 SQL
企业级框架 数据库管理有:Hibernate、MyBatis、Spring Data JPA、MyBatis Plus
MyBatis
MyBatis 是目前主流的 ORM 框架,Apache
ORM:Object Relationship Mapping 对象关系映射
把面向对象的编程语言和关系性数据库进行映射
把 Java 和 MySQL 进行映射
MyBatis 以前叫 iBatis
1、MyBatis 的优势
- 极大简化 JDBC 代码的开发
- 简单易上手、具有很强的灵活性
- SQL 写到 XML 中,实现和 Java 代码的解耦合
- 支持动态 SQL,可以根据具体业务灵活实现需求
2、MyBatis 的缺点
- 相比于 Hibernate,开发者需要完成更多的工作,定义 SQL,完成结果集和实体类的匹配。
- 要求开发人员具备一定的 SQL 编写能力。
- 数据库移植性较差,因为 SQL 依赖于底层数据库的,如果要进行数据库迁移,部分 SQL 需要重新编写。
3、MyBatis 的使用
Maven:管理 jar 的工具
Maven 提供了一个远程仓库,Java 生态中所有框架的 jar 包依赖都会上传到远程仓库,
开发者需要哪个 jar 只需要通过简单的配置从远程仓库下载 jar 到本地即可使用。
导入 jar 的顺序:
1、pom.xml 配置你需要的 jar
2、会在本地仓库进行查找,如果本地仓库存在,则直接导入
3、如果本地仓库没有这个 jar,则需要联网去远程仓库下载
首先需要在本地配置 Maven 环境
1、下载 Maven 文件
2、配置环境变量
Maven 换源 更换远程仓库数据源
更换为国内的阿里云镜像仓库,下载速度会很快
4、使用 Maven 搭建 MyBatis 项目
pom:project object model 工程对象模型
jar 包管理全部通过修改 pom.xml 来实现
1、pom.xml 添加依赖
<dependencies><!-- MyBatis --><dependency><groupId>org.mybatis</groupId><artifactId>mybatis</artifactId><version>3.5.7</version></dependency><!-- MySQL --><dependency><groupId>mysql</groupId><artifactId>mysql-connector-java</artifactId><version>8.0.25</version></dependency>
</dependencies>
2、创建实体类
package com.southwind.entity;import lombok.Data;@Data
public class User {private Integer id;private String name;private Integer money;
}
3、配置数据源,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">
<configuration><!-- 数据源 --><environments default="dev"><environment id="dev"><transactionManager type="JDBC"></transactionManager><dataSource type="POOLED"><property name="driver" value="com.mysql.cj.jdbc.Driver"/><property name="url" value="jdbc:mysql://localhost:3306/test2"/><property name="username" value="root"/><property name="password" value="123456"/></dataSource></environment></environments></configuration>
4、调用 API 完成操作
- 使用原生接口
第一步、创建 Mapper 文件 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">
<mapper namespace="com.southwind.mapper.UserMapper"><select id="get" parameterType="int" resultType="com.southwind.entity.User">select * from user where id = #{id}</select></mapper>
第二步、config.xml 注册 UserMapper.xml
<!-- 注册UserMapper.xml -->
<mappers><mapper resource="com/southwind/mapper/UserMapper.xml"></mapper>
</mappers>
第三步、调用原生接口执行 SQL 获取结果
package com.southwind.test;import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;import java.io.InputStream;public class Test {public static void main(String[] args) {//加载MyBatis配置文件InputStream inputStream = Test.class.getClassLoader().getResourceAsStream("config.xml");//构建SqlSessionFactoryBuilderSqlSessionFactoryBuilder builder = new SqlSessionFactoryBuilder();SqlSessionFactory factory = builder.build(inputStream);//获取SqlSessionSqlSession sqlSession = factory.openSession();String statement = "com.southwind.mapper.UserMapper.get";Object o = sqlSession.selectOne(statement, 1);System.out.println(o);}
}
注意:
1、Maven 默认 JDK 是 1.5,所以需要手动进行升级
<plugins><!-- 设置jdk版本 --><plugin><groupId>org.apache.maven.plugins</groupId><artifactId>maven-compiler-plugin</artifactId><configuration><source>1.8</source><target>1.8</target><encoding>utf-8</encoding></configuration></plugin>
</plugins>
2、默认无法读取 src 路径下的 XML 文件,需要手动进行修改
<resources><resource><directory>src/main/java</directory><includes><include>**/*.xml</include></includes></resource>
</resources>
- Mapper 代理实现自定义接口
5、使用 MyBatis 的注意事项
1、Mapper.xml(SQL语句所在的文件) 必须要在 config.xml(全局环境配置)中进行注册,才可以使用,否则会抛出异常。
2、statement 值必须是 Mapper 接口的命名空间+方法id
3、需要修改 pom.xml ,让 src 路径下的 XML 可以被读取
<resources><resource><directory>src/main/java</directory><includes><include>**/*.xml</include></includes></resource>
</resources>
Maven 工程中默认只能读取 resources 路径下的 XML,src 路径下的 XML 无法读取,所以会报错,所以需要手动进行设置。
6、自定义接口
推荐使用,解决原生接口所带来的问题
Free MyBatis 很实用的 MyBatis 插件
1、自定义接口
package com.southwind.mapper;import com.southwind.entity.User;import java.util.List;public interface UserMapper {public User findById(Integer id);public List<User> findAll();public int save(User user);public int deleteById(Integer id);public int update(User user);
}
2、接口对应的 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">
<mapper namespace="com.southwind.mapper.UserMapper"><insert id="save" parameterType="com.southwind.entity.User">insert into user(name,money) values(#{name},#{money})</insert><update id="update" parameterType="com.southwind.entity.User">update user set name = #{name},money = #{money} where id = #{id}</update><delete id="deleteById" parameterType="java.lang.Integer">delete from user where id = #{id}</delete><select id="findById" parameterType="java.lang.Integer" resultType="com.southwind.entity.User">select * from user where id = #{id}</select><select id="findAll" resultType="com.southwind.entity.User">select * from user</select></mapper>
XML 的命名空间为接口的全类名
每一个 statement 的 id 对应接口的方法名,参数和返回值类型也需要匹配
3、config.xml 中注册 Mapper.xml
<mappers><mapper resource="com/southwind/mapper/UserMapper.xml"></mapper>
</mappers>
4、调用 API
System.out.println(mapper.findById(1));List<User> all = mapper.findAll();
for (User user : all) {System.out.println(user);
}User user = new User();
user.setUserName("小王");
user.setUserMoney(600);
int save = mapper.save(user);
System.out.println(save);
//增删改需要提交事务,查询不需要
sqlSession.commit();User user = mapper.findById(1);
user.setUserName("小黄");
user.setUserMoney(2000);
int update = mapper.update(user);
System.out.println(update);
sqlSession.commit();System.out.println(mapper.deleteById(4));
sqlSession.commit();
7、MyBatis 底层实现
功能:
- 自定义接口
- XML 中定义接口方法对应的 SQL 语句
- 根据 XML,通过 JDK 动态代理(反射)完成自定义接口的具体实现
- 自动解析结果集,映射成 XML 中配置的 JavaBean
技术:
- XML 解析
- Mapper 代理机制通过 JDK 动态代理,掌握反射
8、parameterType
设置参数数据类型,支持基本数据类型、包装类、String、多个参数、Java 对象
1、基本数据类型
public User findById(int id);
<select id="findById" parameterType="int" resultMap="userMap">select * from user where id = #{id}
</select>
#{id} 可以任意替换,因为只有一个参数,所以无论映射名是什么都可以完成映射
2、包装类
public User findById(Integer id);
<select id="findById" parameterType="java.lang.Integer" resultMap="userMap">select * from user where id = #{abc}
</select>
3、String
public User findByName(String name);
<select id="findByName" parameterType="java.lang.String" resultMap="userMap">select * from user where name = #{abc}
</select>
4、多个参数
多个参数的情况下,无法通过映射名来进行映射,而应该采用下标进行映射
arg0、arg1、param1、param2
public User findByIdAndName(Integer id,String name);
<select id="findByIdAndName" resultMap="userMap">select * from user where id = #{param1} and name = #{param2}
</select>
5、Java 对象
参数列表中的映射名就是实体类的属性名
public User findByUser(User user);
<select id="findByUser" parameterType="com.southwind.entity.User" resultMap="userMap">select * from user where name = #{userName} and money = #{userMoney}
</select>
9、resultType
1、基本数据类型
public int count();
<select id="count" resultType="int">select count(id) from user
</select>
2、包装类
public Integer count();
<select id="count" resultType="java.lang.Integer">select count(id) from user
</select>
3、String
public String findNameById(Integer id);
<select id="findNameById" parameterType="java.lang.Integer" resultType="java.lang.String">select name from user where id = #{id}
</select>
4、Java 对象
public User findById(Integer id);
<select id="findById" parameterType="java.lang.Integer" resultMap="userMap">select * from user where id = #{abc}
</select>
10、多表关联查询
1、一对多
如果查询出来的结果是 null
1、数据确实不存在
2、数据存在,但是字段无法和实体类属性名进行映射
package com.southwind.entity;import lombok.Data;@Data
public class Student {private Integer id;private String name;private Class aClass;
}
package com.southwind.entity;import lombok.Data;@Data
public class Class {private Integer id;private String name;
}
package com.southwind.mapper;import com.southwind.entity.Student;public interface StudentMapper {public Student findById(Integer id);
}
<?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">
<mapper namespace="com.southwind.mapper.StudentMapper"><resultMap id="studentMap" type="com.southwind.entity.Student"><id column="sid" property="id"></id><result column="sname" property="name"></result><association property="aClass" javaType="com.southwind.entity.Class"><id column="cid" property="id"></id><result column="cname" property="name"></result></association></resultMap><select id="findById" resultMap="studentMap">select s.id sid,s.name sname,c.id cid,c.name cnamefrom student s,class c where s.cid = c.id and s.id = #{id}</select></mapper>
TooManyResultsException: Expected one result (or null) to be returned by selectOne(), but found: 2
查询出来的结果集和实体类无法映射,接口方法返回值要求是一个对象,但是查出来多条结果。
package com.southwind.entity;import lombok.Data;import java.util.List;@Data
public class Class {private Integer id;private String name;private List<Student> students;
}
package com.southwind.mapper;import com.southwind.entity.Class;public interface ClassMapper {public Class findById(Integer id);
}
2、多对多关系
package com.southwind.m2mentity;import lombok.Data;import java.util.List;@Data
public class Course {private Integer id;private String name;private List<User> users;
}
package com.southwind.m2mentity;import lombok.Data;import java.util.List;@Data
public class User {private Integer id;private String name;private List<Course> courses;
}
package com.southwind.mapper;import com.southwind.m2mentity.Course;public interface CourseMapper {public Course findById(Integer id);
}
<?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">
<mapper namespace="com.southwind.mapper.CourseMapper"><resultMap id="courseMap" type="com.southwind.m2mentity.Course"><id column="cid" property="id"></id><result column="cname" property="name"></result><collection property="users" ofType="com.southwind.m2mentity.User"><id column="uid" property="id"></id><result column="uname" property="name"></result></collection></resultMap><select id="findById" parameterType="java.lang.Integer" resultMap="courseMap">select u.id uid,u.name uname,c.id cid,c.name cname from user u,course c,user_course ucwhere u.id = uc.uid and c.id = uc.cid and c.id = #{id}</select></mapper>
11、MyBatis 延迟加载
将某些加载(查询数据库)进行滞后操作,尽量减少 SQL 的执行,从而达到提高速度的目的,是对数据库操作的一种优化。
延迟加载(按需加载、懒加载)只存在于级联查询中,单表查询没有延迟加载的功能。
查询学生–>班级
MyBatis 打印 SQL
<settings><!-- 打印SQL --><setting name="logImpl" value="STDOUT_LOGGING"/>
</settings>
同样的结果,但是 SQL 语句不同,尽量选择效率最高的 SQL 去执行。
1、多表关联查询的 SQL 拆分成两个 SQL 。
单独 SQL 查询 student
单独 SQL 查询 class
1、select * from student where id = 1;
查询出 student 的相关信息,再去查询级联的 class 信息
2、select * from class where id = 1
第 2 条 SQL 的条件就是第 1 条 SQL 的结果中的 cid
开启延迟加载之前,查询 name 需要执行两条 SQL
2、config.xml 配置文件中开启延迟加载。
开启延迟加载,如果只需要获取 student 的信息,那么只执行第一条 SQL,足够了。
<!-- 延迟加载 -->
<setting name="lazyLoadingEnabled" value="true"/>
如果要获取级联的 class 信息,则第一条 SQL 不够用,此时再去执行第二条 SQL,这就是按需加载。
总结
MyBatis 框架的延迟加载,是实际开发中使用频录较高的功能,正确的使用延迟加载,可以有效减少 Java 程序和数据库的交互次数,从而提升整个系统的运行效率,延迟加载适用于多表关联查询的业务场景。
12、MyBatis 缓存
MyBatis 延迟加载,解决的是多表关联查询情况下的效率问题,但是对于单表查询,延迟加载没有作用,MyBatis 提供了缓存机制来解决单表查询情况下的效率问题。
使用缓存也是通过减少 Java 程序和数据库交互次数来提高查询效率,第一次查询出某个对象之后,MyBatis 会自动将它存入缓存,当下一次查询该对象的时候,可以直接从缓存中获取,不必再次访问数据库。
如果执行删除、修改操作,MyBatis 会自动清楚缓存,从而保证数据的时效性。
MyBatis 有两种缓存:一级缓存和二级缓存,作用域不同
12.1、一级缓存
MyBatis 自带一级缓存,并且无法关闭,一直存在,一级缓存的数据存储在 SqlSession,它的作用域是同一个 SqlSession,当使用同一个 SqlSession 执行查询的时候,第一次的结果会自动存入 SqlSession 缓存,第二次查询可以直接获取。
如果是两个不同的 SqlSession,则一级缓存不会生效。
package com.southwind.test;import com.southwind.entity.Class;
import com.southwind.entity.Student;
import com.southwind.entity.User;
import com.southwind.mapper.*;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;import java.io.InputStream;
import java.util.List;public class Test {public static void main(String[] args) {//加载MyBatis配置文件InputStream inputStream = Test.class.getClassLoader().getResourceAsStream("config.xml");//构建SqlSessionFactoryBuilderSqlSessionFactoryBuilder builder = new SqlSessionFactoryBuilder();SqlSessionFactory factory = builder.build(inputStream);//获取SqlSessionSqlSession sqlSession = factory.openSession();//通过sqlSession获取代理对象StudentMapper mapper = sqlSession.getMapper(StudentMapper.class);Student student = mapper.selectById(1);System.out.println(student);//获取新的sqlSessionsqlSession = factory.openSession();mapper = sqlSession.getMapper(StudentMapper.class);Student student1 = mapper.selectById(1);System.out.println(student1);}
}
12.2、二级缓存
一级缓存不需要进行任何配置,可以直接使用。
当一级缓存失效的时候,可以开启二级缓存,同样实现数据共享的功能,二级缓存是比一级缓存作用域更大的缓存机制,它是 Mapper 级别的,只要是同一个 Mapper,无论使用多少个 SqlSession 来创建,数据都是共享的,多个 SqlSession 可以共用二级缓存。
MyBatis 二级缓存默认是关闭的,需要使用的时候可以通过手动设置来开启。
1、config.xml 配置文件中开启二级缓存。
<!-- 开启二级缓存 -->
<setting name="cacheEnabled" value="true"/>
2、Mapper.xml 中配置二级缓存
<cache></cache>
3、实体类实现 Serializable 接口
package com.southwind.entity;import lombok.Data;import java.io.Serializable;@Data
public class Student implements Serializable {private Integer id;private String name;private Class aClass;
}
4、测试
package com.southwind.test;import com.southwind.entity.Class;
import com.southwind.entity.Student;
import com.southwind.entity.User;
import com.southwind.mapper.*;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;import java.io.InputStream;
import java.util.List;public class Test {public static void main(String[] args) {//加载MyBatis配置文件InputStream inputStream = Test.class.getClassLoader().getResourceAsStream("config.xml");//构建SqlSessionFactoryBuilderSqlSessionFactoryBuilder builder = new SqlSessionFactoryBuilder();SqlSessionFactory factory = builder.build(inputStream);//获取SqlSessionSqlSession sqlSession = factory.openSession();//通过sqlSession获取代理对象StudentMapper mapper = sqlSession.getMapper(StudentMapper.class);Student student = mapper.selectById(1);System.out.println(student);sqlSession.close();//获取新的sqlSessionsqlSession = factory.openSession();mapper = sqlSession.getMapper(StudentMapper.class);Student student1 = mapper.selectById(1);System.out.println(student1);}
}
要使用二级缓存,第一次使用的 SqlSession必须关闭,否则二级缓存无法开启。
SqlSession 在没有提交的情况下,不会将数据同步到二级缓存中,所以会导致第二次查询仍然要执行 SQL,所以一般执行完毕之后需要关闭 SqlSession,关闭的同时会自动提交。
12.3、总结
MyBatis 框架的缓存分为两种:一级缓存和二级缓存,一级缓存是 SqlSession 级别的,二级缓存是 Mapper 级别的,使用的时候需要注意两种缓存的区别,作用域不同,一级缓存是默认开启且无法关闭的,二级缓存需要手动开启。
缓存机制和延迟加载功能类似,都是通过减少 Java 程序和数据库的交互次数来提高系统的运行速度,缓存机制更多针对于单表查询,延迟加载更多针对多表关联查询。
缓存机制使用的前提是两次查询直接没有修改、删除的操作,如果有修改、删除的操作,那么缓存就会自动清空,从而保证数据的时效性。
13、MyBatis 动态 SQL
- id 和 username 查询
- username 和 password 查询
- password 和 age 查询
<?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">
<mapper namespace="com.mapper.UserMapper"><select id="findByUser1" resultType="com.domain.User">select * from user where id = #{id} and username = #{username}</select><select id="findByUser2" resultType="com.domain.User">select * from user where password = #{password} and username = #{username}</select><select id="findByUser3" resultType="com.domain.User">select * from user where password = #{password} and age = #{age}</select></mapper>
代码复用性很差,可以使用动态 SQL 来解决这个问题。
判断条件是否成立,如果成立则追加 if 标签中的内容,如果不成立,则不追加内容
自动判断 where 后面是否直接跟 and,如果是则删除 and,如果不是则保留 and
<select id="findByUser" resultType="com.domain.User">select * from user<where><if test="id != null">id = #{id}</if><if test="username != null">and username = #{username}</if><if test="password != null">and password = #{password}</if><if test="age != null">and age = #{age}</if></where>
</select>
作用和 if 标签一致
<select id="findByUser" resultType="com.domain.User">select * from user<where><choose><when test="id != null">id = #{id}</when><when test="username != null">and username = #{username}</when><when test="password != null">and password = #{password}</when><when test="age != null">and age = #{age}</when></choose></where>
</select>
prefix 中的值,如果和 prefixOverrides 中的值直接拼接,则自动删除 prefixOverrides 中的值。
<select id="findByUser" resultType="com.domain.User">select * from user<trim prefix="where" prefixOverrides="and"><if test="id != null">id = #{id}</if><if test="username != null">and username = #{username}</if><if test="password != null">and password = #{password}</if><if test="age != null">and age = #{age}</if></trim>
</select>
用于 update 操作,会自动根据参数选择生成 SQL 语句
<update id="update">update user<set><if test="username != null">username = #{username},</if><if test="password != null">password = #{password},</if><if test="age != null">age = #{age}</if></set>where id = #{id}
</update>
可以迭代生成一系列的值,这个标签主要用于 SQL 的 in 语句。
<select id="findByUser" parameterType="com.domain.User" resultType="com.domain.User">select * from user<where><foreach collection="ids" item="id" open="id in (" close=")" separator=",">#{id}</foreach></where>
</select>