简介
什么是Mybatis?
- MyBatis 是一款优秀的持久层框架.
- 它支持自定义 SQL、存储过程以及高级映射。
- MyBatis 免除了几乎所有的 JDBC 代码以及设置参数和获取结果集的工作。
- MyBatis 可以通过简单的 XML 或注解来配置和映射原始类型、接口和 Java POJO(Plain Old Java Objects,普通老式 Java 对象)为数据库中的记录。
- MyBatis 本是apache的一个开源项目叫做 iBatis,
- 2010年这个项目由apache software foundation 迁移到了[google code](https://baike.baidu.com/item/google code/2346604),并且改名为MyBatis 。
- 2013年11月迁移到Github。
- 官网中文文档 点击进入
如何获得Mybatis
- Maven仓库
<!-- https://mvnrepository.com/artifact/org.mybatis/mybatis -->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.5.6</version>
</dependency>
- Github :Github下载链接
数据持久化
-
持久化就是将程序的数据在持久状态和瞬时状态转化的过程。
-
内存: 断电即失。
-
持久化的方式有: 数据库,IO文件持久化 等。
为什么需要持久化?
- 有一些对象及数据,不能让它丢掉。
- 内存太贵。
- …
持久层
常见的层: 如 Dao层,Service层,Controller层…
为什么需要Mybatis?
-
帮助程序猿将数据存入数据库中。
-
方便
-
传统的JDBC代码过于复杂。简化,框架,自动化。
-
不用Mybatis也可以。(技术没有高低之分)
-
特点及优点:
- 简单易学:通过文档和源代码,可以比较完全的掌握它的设计思路和实现。
- 灵活: sql写在xml里,便于统一管理和优化。通过sql语句可以满足操作数据库的所有需求。
- 解除sql与程序代码的耦合:通过提供DAO层,将业务逻辑和数据访问逻辑分离,sql和代码的分离,提高了可维护性。
- 提供映射标签,支持对象与数据库的orm字段关系映射
- 提供对象关系映射标签,支持对象关系组建维护
- 提供xml标签,支持编写动态sql。
-
最重要的原因: 使用的人多。
Mybatis的执行原理
从图中可以看出,mybatis中首先要在配置文件中配置一些东西,然后根据这些配置去创建一个会话工厂,再根据会话工厂创建会话,会话发出操作数据库的sql语句,然后通过执行器操作数据,再使用mappedStatement对数据进行封装,这就是整个mybatis框架的执行情况
。
第一个Mybatis程序
思路: 搭建环境–>导入mybatis等jar包–>编写代码–>测试!
搭建环境
搭建数据库及数据表
新建项目
- 新建一个普通的maven项目
- 删除src目录(便于创建父子工程)
- 在pom.xml中导入相关依赖
<!--导入依赖-->
<!--1.mysql驱动依赖-->
<dependencies>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.19</version>
</dependency>
<!--2.mybatis依赖-->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.5.6</version>
</dependency>
<!--3.Junit依赖-->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
</dependency>
</dependencies>
创建一个模块
- 编写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核心配置文件-->
<configuration>
<environments default="development">
<environment id="development">
<transactionManager type="JDBC"/> <!--事务管理是JDBC-->
<dataSource type="POOLED">
<!--更换连接数据库的各个属性值-->
<property name="driver" value="com.mysql.cj.jdbc.Driver"/>
<!--注:这里的&连接符要用&进行表示,& 是 HTML 中 & 的表示方法-->
<property name="url" value="jdbc:mysql://localhost:3306/mybatis?serverTimezone=UTC&useUnicode=true&characterEncoding=utf-8&useSSL=true"/>
<property name="username" value="root"/>
<property name="password" value="root"/>
</dataSource>
</environment>
</environments>
<!--每一个Mapper.xml都需要在mybatis的核心配置文件中注册-->
<mappers>
<!--路径要用/进行分割-->
<mapper resource="com/carson/dao/UserMapper.xml"/>
</mappers>
</configuration>
- 编写mybatis工具类(专门生成sqlSession,其类似于connection)
//sqlSessionFactory-->产生sqlSession
public class MybatisUtils {
//提升作用域
private static SqlSessionFactory sqlSessionFactory;
//通过SqlSessionFactoryBuilder读取配置文件的方式产生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 getSqlSession(){
return sqlSessionFactory.openSession();
}
}
编写代码
- 实体类
package com.carson.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;
}
}
- Dao接口
public interface UserDao {
public List<User> getUserList();
}
- 接口实现类(由原来的UserDaoImpl转变为一个Mapper配置文件)
这种mapper配置文件,可以上mybatis的官网找一个demo配置文件,把它copy过来进行修改即可!
<?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接口 路径写全-->
<mapper namespace="com.carson.dao.UserDao">
<!--select标签对应select查询语句-->
<!--id对应要实现的接口的方法的名字,resultType对应返回类型且路径要写全-->
<select id="getUserList" resultType="com.carson.pojo.User">
select * from mybatis.user
</select>
</mapper>
测试
使用Junit进行测试
package com.carson.dao;
import com.carson.pojo.User;
import com.carson.utils.MybatisUtils;
import org.apache.ibatis.session.SqlSession;
import org.junit.Test;
import java.util.List;
public class UserDaoTest {
@Test
public void test(){
//第一步,获得sqlSession对象
SqlSession sqlSession = MybatisUtils.getSqlSession();
//方式一:getMapper
UserDao userDao = sqlSession.getMapper(UserDao.class);
List<User> userList = userDao.getUserList();
//方式二:(不推荐)
//List<User> userList = sqlSession.selectList("com.carson.dao.UserDao.getUserList");
for(User user:userList){
System.out.println(user);
}
//关闭sqlSession
sqlSession.close();
}
}
可能遇到的问题?
- maven中常遇到的xml资源导出失败问题。
标准的Maven项目都会有一个resources目录来存放我们所有的资源配置文件,但是我们往往在项目中不仅仅会把所有的资源配置文件都放在resources中,同时我们也有可能放在项目中的其他位置,那么默认的maven项目构建编译时就不会把我们其他目录下的资源配置文件导出到target目录中,就会导致我们的资源配置文件读取失败,从而导致我们的项目报错出现异常,比如说尤其我们在使用MyBatis框架时,往往Mapper.xml配置文件都会放在dao包中和dao接口类放在一起的,那么执行程序的时候,其中的xml配置文件就一定会读取失败,不会生成到maven的target目录中,所以我们要在项目的pom.xml文件中进行设置,并且我建议大家,每新建一个maven项目,就把该设置导入pom.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>
- Caused by: com.sun.org.apache.xerces.internal.impl.io.MalformedByteSequenceException: 1 字节的 UTF-8 序列的字节 1 无效。
- Caused by: com.sun.org.apache.xerces.internal.impl.io.MalformedByteSequenceException: 2 字节的 UTF-8 序列的字节 2 无效。
上面两种情况(即 xml文件输出的中文乱码)问题解决方案:
- 当两个xml文件中(mybatis-config.xml和UserMapper.xml)含有中文注释时:
- 将mybatis两个xml配置文件(mybatis-config.xml和UserMapper.xml)中首行的encoding="UTF-8"中的-去掉,即改为:encoding=“UTF8”
- 将encoding="UTF-8"更改为:encoding=“GBK”,因为JDK会以操作系统默认的编码格式去编码,而我们电脑的默认编码是GBK。
- 将电脑的JDK默认编码改为UTF-8,这里就不会报错。
更改方式: 参考链接
- 当两个xml文件中(mybatis-config.xml和UserMapper.xml)没有中文注释时:
- 由于不含由中文,不会出现xml文件的中文乱码问题配置文件不用做更改,即: encoding="UTF-8"还是encoding=“UTF-8”
其它可能遇到的问题:
- 实现接口的配置文件没有在mybatis的核心配置文件中进行注册
- 绑定接口错误
- 方法名不对
- 返回类型不对
步骤总结:
- 编写创建sqlSessionFactory的工具类
- 编写mybatis的核心配置文件
- 编写pojo实体类
- 编写接口
- 编写接口实现的配置文件
- 编写测试代码
Mybatis的CRUD
注: 一切的增删改都要处理事务。
1.namespace
-
实现接口的配置文件中namespace要和Dao/Mapper接口名一致。
-
即namespace就是实现的接口名(要写全路径)。
2.select标签
- 实现接口的配置文件中的select标签中的id 表示需要重写的接口里的方法名。
- resultType: 即sql语句执行的返回值!(复杂数据类型要写全路径)
- parameterType: 参数类型
- 编写接口方法
public interface UserMapper {
//查询全部用户
public List<User> getUserList();
//根据Id查询用户
public User getUserById(int id);
}
- 编写对应的mapper配置文件中的sql语句
<mapper namespace="com.carson.dao.UserMapper">
<!--select标签对应select查询语句-->
<!--id对应要实现的接口的方法的名字,resultType对应返回类型且路径要写全-->
<select id="getUserList" resultType="com.carson.pojo.User">
select * from mybatis.user;
</select>
<!--select查询语句 #{变量名}形式去填写sql语句的参数-->
<select id="getUserById" parameterType="int" resultType="com.carson.pojo.User">
select * from user where id = #{id};
</select>
- 编写测试代码
//查询全部用户
@Test
public void test(){
//第一步,获得sqlSession对象
SqlSession sqlSession = MybatisUtils.getSqlSession();
try{
//方式一:getMapper(获取接口对象,调用方法)
UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
List<User> userList = userMapper.getUserList();
//方式二:(不推荐)
//List<User> userList = sqlSession.selectList("com.carson.dao.UserDao.getUserList");
for(User user:userList){
System.out.println(user);
}
}catch (Exception e){
e.printStackTrace();
}finally {
//关闭sqlSession
sqlSession.close();
}
}
//根据id查询用户
@Test
public void getUserById(){
SqlSession sqlSession = MybatisUtils.getSqlSession();
try{
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
User user = mapper.getUserById(2);
System.out.println(user);
}catch (Exception e){
e.printStackTrace();
}finally {
sqlSession.close();
}
}
3.insert标签
- 编写接口方法
//增加一个用户
public int addUser(User user);
- 编写对应的mapper配置文件中的sql语句
<!--insert语句 对应 insert标签-->
<!--对象中的属性,可以直接取出来-->
<insert id="addUser" parameterType="com.carson.pojo.User">
insert into user values(#{id},#{name},#{pwd});
</insert>
- 编写测试代码
//增加一个用户
@Test
public void addUser(){
SqlSession sqlSession = MybatisUtils.getSqlSession();
try{
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
int affectedRows = mapper.addUser(new User(5, "test", "111111"));
if(affectedRows>0){
//由于一切的增删改都要处理事务,这里要提交事务
sqlSession.commit();
System.out.println("插入成功!");
}
}catch (Exception e){
//出现错误,事务回滚
sqlSession.rollback();
e.printStackTrace();
}finally {
sqlSession.close();
}
}
4.update标签
- 编写接口方法
//修改一个用户
public int updateUser(User user);
- 编写对应的mapper配置文件中的sql语句
<!--update语句 对应 update标签-->
<!--对象中的属性,可以直接取出来-->
<update id="updateUser" parameterType="com.carson.pojo.User">
update user set name=#{name},pwd=#{pwd} where id=#{id};
</update>
- 编写测试代码
//修改一个用户
@Test
public void updatUser(){
SqlSession sqlSession = MybatisUtils.getSqlSession();
try{
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
int affectedRows = mapper.updateUser(new User(5,"test0","000000"));
if(affectedRows>0){
//由于一切的增删改都要处理事务,这里要提交事务
sqlSession.commit();
System.out.println("修改成功!");
}
}catch (Exception e){
//出现错误,事务回滚
sqlSession.rollback();
e.printStackTrace();
}finally {
sqlSession.close();
}
}
5.delete标签
- 编写接口方法
//删除一个用户
public int delUser(int id);
- 编写对应的mapper配置文件中的sql语句
<!--delete语句 对应 delete标签-->
<delete id="delUser" parameterType="int">
delete from user where id = #{id};
</delete>
- 编写测试代码
//删除一个用户
@Test
public void delUser(){
SqlSession sqlSession = MybatisUtils.getSqlSession();
try{
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
int affectedRows = mapper.delUser(5);
if(affectedRows>0){
//由于一切的增删改都要处理事务,这里要提交事务
sqlSession.commit();
System.out.println("删除成功!");
}
}catch (Exception e){
//出现错误,事务回滚
sqlSession.rollback();
e.printStackTrace();
}finally {
sqlSession.close();
}
}
6.实现模糊查询
-
方式一: 在java代码执行的时候,给实参传递通配符% %
接口方法:
//模糊查询示例
public List<User> getUserListLike(String value);
实现的接口方法的配置文件:
<!--模糊查询示例-->
<select id="getUserListLike" resultType="com.carson.pojo.User">
select * from user where name like #{value };
</select>
测试代码:
//模糊查询示例
@Test
public void getUserListLike(){
SqlSession sqlSession = MybatisUtils.getSqlSession();
try{
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
List<User> users = mapper.getUserListLike("%李%");
for (User user : users) {
System.out.println(user);
}
}catch (Exception e){
e.printStackTrace();
}finally {
sqlSession.close();
}
}
- 方式二: 直接在sql拼接中使用通配符!
接口方法:
//模糊查询示例
public List<User> getUserListLike(String value);
实现的接口方法的配置文件:
<!--模糊查询示例-->
<select id="getUserListLike" resultType="com.carson.pojo.User">
select * from user where name like "%"#{value}"%";
</select>
测试代码:
//模糊查询示例
@Test
public void getUserListLike(){
SqlSession sqlSession = MybatisUtils.getSqlSession();
try{
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
List<User> users = mapper.getUserListLike("李");
for (User user : users) {
System.out.println(user);
}
}catch (Exception e){
e.printStackTrace();
}finally {
sqlSession.close();
}
}
7.Mybatis中的 #{} 和 ${}区别
Mybatis 的Mapper.xml语句中向SQL语句传参有两种方式:
即: #{} 和 ${}
- 我们经常使用的是#{},一般解说是因为这种方式可以防止SQL注入,简单的说#{}这种方式SQL语句是经过预编译的,它是把#{}中间的参数转义成字符串,举个例子:
select * from student where student_name = #{name}
预编译后,会动态解析成一个参数标记符 ? :
select * from student where student_name = ?
- 而使用${}在动态解析时候,会传入参数字符串
select * from student where student_name = 'carson'
总结:
-
#{} 这种取值是编译好SQL语句再取值, 使用的是预编译, 对应JBDC中的PreparedStatement, 使用#{}时,具体的SQL语句的参数会加上单引号.
-
${} 这种是取值以后再去编译SQL语句, mybatis不会修改或者转义字符换,直接输出变量值,即不会对参数加引号。
-
#{}方式能够很大程度防止sql注入。$方式无法防止Sql注入。
-
一般能用#{}的 就别用 ${}
8. jdbcType
在mapper.xml中,写java类映射数据库表字段的时候,有jdbcType,之前并没有很注意,发现有些人习惯在写mybatis写sql的时候,映射关联参数时喜欢加上jdbcType=xxx
,如下:
<insert id="insert" parameterType="java.xx.xx" >
insert into table_xxx values(name = #{name,jdbcType=VARCHAR})
</insert>
例如上面的jdbcType=VARCHAR,这是为了程序的安全性,使一些特殊情况,当传入的参数为name为空时不会使程序出现问题,当name为空时,mybatis不知道具体要转换成什么jdbcType类型,有些特殊情况会报错,Mybatis经常出现的:无效的列类型: 1111 错误,就是因为没有设置JdbcType造成的
。
以后还是必须加jdbcType了,下面给出一些常见的jdbcType和java类型的对应:
JDBC Type | Java Type |
---|---|
CHAR | String |
VARCHAR | String |
LONGVARCHAR | String |
NUMERIC | java.math.BigDecimal |
DECIMAL | java.math.BigDecimal |
BIT | boolean |
BOOLEAN | boolean |
TINYINT | byte |
SMALLINT | short |
INTEGER | INTEGER |
BIGINT | long |
REAL | float |
FLOAT | double |
DOUBLE | double |
BINARY | byte[] |
VARBINARY | byte[] |
LONGVARBINARY | byte[] |
DATE | java.sql.Date |
TIME | java.sql.Time |
TIMESTAMP | java.sql.Timestamp |
CLOB | Clob |
BLOB | Blob |
ARRAY | Array |
DISTINCT | mapping of underlying type |
STRUCT | Struct |
REF | Ref |
DATALINK | java.net.URL |
9.万能的Map
假设,我们的实体类或者数据库中表的 字段或者参数过多,我们应当考虑使用Map!
示例如下:
- 编写接口方法(传递Map类型参数)
//使用万能的Map来传递参数
public int addUser2(Map<String,Object> map);
- 编写对应的mapper配置文件中的sql语句
<!--使用map的key值作为参数进行传递,而key值的名字可以不和数据库中的字段名一样-->
<insert id="addUser2" parameterType="map">
insert into user values (#{mapId},#{mapName},#{mapPwd});<!--传递Map的key-->
</insert>
- 编写测试代码
//增加一个用户(传递Map的key值)
@Test
public void addUser2(){
SqlSession sqlSession = MybatisUtils.getSqlSession();
try{
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
//建立map
Map<String, Object> map = new HashMap<String, Object>();
map.put("mapId",5);
map.put("mapName","mapTest");
map.put("mapPwd","654545");
int affectedRows = mapper.addUser2(map);
if(affectedRows>0){
//增删改需要处理事务,这里提交事务
sqlSession.commit();
System.out.println("Map方式增加成功!");
}
}catch (Exception e){
//出现异常,事务回滚
sqlSession.rollback();
e.printStackTrace();
}finally{
sqlSession.close();
}
}
注:
-
Map传递参数,直接在sql中取出key即可!【parameterType=“map”】
-
对象传递参数,直接在sql中取对象的属性即可!
【parameterType=“实体对象的全路径”】
-
只有一个基本数据类型的参数的情况,可以直接在sql中取到!
【parameterType=“基本数据类型”】或者 不用写参数类型。
建议: 多个参数用Map 或者 注解!
配置解析
1.核心配置文件
-
即: mybatis-config.xml
-
mybatis的配置文件包含了会深深影响mybatis行为的设置和属性信息
- properties(属性)
- settings(设置)
- typeAliases(类型别名)
- typeHandlers(类型处理器)
- objectFactory(对象工厂)
- plugins(插件)
- environments(环境配置)
- environment(环境变量)
- transactionManager(事务管理器)
- dataSource(数据源)
- environment(环境变量)
- databaseIdProvider(数据库厂商标识)
- mappers(映射器)
2.环境配置(environments)
Mybatis可以配置成适应多种环境。
不过要记住:尽管可以配置多个环境,但配置文件里只能选择一种环境
Mybatis默认的事务管理器就是JDBC, 默认的数据源: POOLED(连接池)
学会使用配置多套运行环境。(示例更改环境为test)
<?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">
现在通过default改为test(对应更改环境的id)-->
<environments default="test">
<environment id="development">
<transactionManager type="JDBC"/>
<dataSource type="POOLED">
<property name="driver" value="com.mysql.cj.jdbc.Driver"/>
<property name="url" value="jdbc:mysql://localhost:3306/mybatis?serverTimezone=UTC&useUnicode=true&characterEncoding=utf-8&useSSL=true"/>
<property name="username" value="root"/>
<property name="password" value="root"/>
</dataSource>
</environment>
<!--可以配置多套环境-->
<environment id="test">
<transactionManager type="JDBC"></transactionManager>
<dataSource type="POOLED">
<property name="driver" value="com.mysql.cj.jdbc.Driver" />
<property name="url" value="jdbc:mysql://localhost:3306/mybatis?serverTimezone=UTC&useUnicode=true&characterEncoding=utf-8&useSSL=true"/>
</dataSource>
</environment>
</environments>
<!--每一个Mapper.xml都需要在mybatis的核心配置文件中注册-->
<mappers>
<!--路径要用/进行分割-->
<mapper resource="com/carson/dao/UserMapper.xml"/>
</mappers>
</configuration>
3.属性(properties)
我们可以通过properties标签来实现引用配置文件。
这些属性都是可外部配置且动态替换的, 既可以在典型的Java属性文件中配置, 亦可通过properties元素的 子元素标签property 来传递(即上面代码中property设置name属性和value属性的方式 来创建键值对)。
properties引用外部配置文件示例:
- resources资源目录下编写一个配置文件(db.properties)
driver=com.mysql.cj.jdbc.Driver
url=jdbc:mysql://localhost:3306/mybatis?serverTimezone=UTC&useUnicode=true&characterEncoding=utf-8&useSSL=true
username=root
password=root
- 在Mybatis的核心配置文件中引入:
注: 如图,xml中元素标签位置是有要求的, 这里的properties标签元素需要放在configuration 标签里面的第一个位置。
- 可以直接引入外部配置文件
<configuration>
<!--引入外部的配置文件-->
<!--由于配置文件在resources资源目录,故文件路径不需要写全路径-->
<properties resource="db.properties"></properties>
<!---------------------------------------------->
<environments default="development">
<environment id="development">
<transactionManager type="JDBC"/>
<dataSource type="POOLED">
<!--value值直接读取配置文件 ${变量名}的方式-->
<property name="driver" value="${driver}"/>
<property name="url" value="${url}"/>
<property name="username" value="${username}"/>
<property name="password" value="${password}"/>
</dataSource>
</environment>
</environments>
- 可以在其中增加一些属性配置。
<configuration>
<!--引入外部的配置文件-->
<!--由于配置文件在resources资源目录,故文件路径不需要写全路径-->
<properties resource="db.properties">
<!--在properties中增加一些属性配置-->
<property name="username" value="root"/>
<property name="password" value="root"/>
</properties>
<!---------------------------------------------->
<environments default="development">
<environment id="development">
<transactionManager type="JDBC"/>
<dataSource type="POOLED">
<!--value值直接读取配置文件 ${变量名}的方式-->
<property name="driver" value="${driver}"/>
<property name="url" value="${url}"/>
<property name="username" value="${username}"/>
<property name="password" value="${password}"/>
</dataSource>
</environment>
</environments>
- 如果外部配置文件中有 和property标签中的属性配置是同一个字段,则优先使用 外部配置文件的字段及其值。
4.类型别名(typeAliases)
- 类型别名是为 Java类型设置一个短的名字
- 存在的意义仅在于用来减少 类完全限定名的冗余
- 方式一: 直接给实体类起别名
<!--可以给实体类起别名 标签顺序是有要求的-->
<typeAliases>
<!--直接给实体类起别名-->
<typeAlias type="com.carson.pojo.User" alias="user" />
</typeAliases>
- 方式二: 可以指定一个包名,Mybatis会在包名下面搜索需要的Java Bean,即通过扫描实体类的包,默认别名就为这个类的类名首字母小写。
<!--可以给实体类起别名 标签顺序是有要求的-->
<typeAliases>
<!--通过扫描实体类所在的包,它的默认别名 就为 这个类的类名的小写-->
<!--这里的包下的类是User, 则默认别名为:user-->
<package name="com.carson.pojo" />
</typeAliases>
注:
-
在实体类比较少的时候,类型别名 推荐使用第一种。
-
如果实体类十分多,类型别名 推荐使用第二种。
-
第一种类型别名的方式可以 DIY别名。
-
第二种类型别名的方式则不能DIY别名; 如果非要改,就需要在实体类上增加注解。即:
@Alias("user") public class User{...}
注: 下面是一些为常见的 Java 类型 内建的类型别名
类别别名 | 映射对应的类型 |
---|---|
_byte | byte |
_long | long |
_short | short |
_int | int |
_double | double |
_float | float |
_boolean | boolean |
string | String |
byte | Byte |
long | Long |
short | Short |
int | Integer |
double | Double |
float | Float |
boolean | Boolean |
date | Date |
decimal | BigDecimal |
object | Object |
map | Map |
hashmap | HashMap |
list | List |
arraylist | ArrayList |
collection | Collection |
iterator | Iterator |
… |
即:基本数据类型的默认别名为: _基本类型
包装类型的默认别名为: 包装类型的小写形式
5.设置
这是Mybatis中极为重要的调整设置,它们会改变 Mybatis的运行时行为。
示例:
6.其它配置
- typeHandlers(类型处理器)
- objectFactory(对象工厂)
- plugins(插件)
- mybatis-generator-core
- mybatis-plus
- 通用mapper
7.映射器(mappers)
MapperRegistry: 注册绑定我们的Mapper文件;
- 方式一:【推荐使用】
<!--每一个Mapper.xml都需要在mybatis的核心配置文件中注册-->
<mappers>
<!--路径要用/进行分割-->
<mapper resource="com/carson/dao/UserMapper.xml"/>
</mappers>
- 方式二:
<!--每一个Mapper.xml都需要在mybatis的核心配置文件中注册-->
<mappers>
<mapper class="com.carson.dao.UserMapper"/>
</mappers>
注意点:
- 接口和它的Mapper配置文件必须同名
- 接口和它的Mapper配置文件必须在同一个包下。
- 方式三: 使用扫描包进行注入绑定
<!--每一个Mapper.xml都需要在mybatis的核心配置文件中注册-->
<mappers>
<package name="com.carson.dao"/>
</mappers>
注意点:
- 接口和它的Mapper配置文件必须同名
- 接口和它的Mapper配置文件必须在同一个包下。
8.生命周期和作用域
生命周期和作用域,是至关重要的,即错误的使用会导致非常严重的并发问题。
SqlSessionFactoryBuilder:
- SqlSessionFactoryBuilder一旦创建了SqlSessionFactory,就不再需要SqlSessionFactoryBuilder了。
- 局部变量。
SqlSessionFactory:
- 相当于一个: 数据库连接池
- SqlSessionFactory一旦被创建就应该在应用的运行期间一直存在,没有理由丢弃它或重新创建一个SqlSessionFactory.
- 因此,SqlSessionFactory的最佳作用域是应用作用域。
- 最简单的就是使用 单例模式 或者 静态单例模式。
SqlSession:
- 相当于连接到连接池的一个请求!
- SqlSession的实例不是线程安全的,因此是不能被共享的,其最佳作用域是请求 或 方法作用域。
- 用完之后要赶紧关闭,否则资源被占用!
这里面的每一个Mapper,就可以代表一个具体的业务。
实体类属性名和数据库表字段名不一致的问题
1. 问题
数据库中的字段:
实体类中的字段:
public class User{
private int id;
private String name;
private String password;
......
}
Mapper.xml文件:
<mapper namespace="com.carson.dao.UserMapper">
<select id="getUserById" parameterType="int" resultType="com.carson.pojo.User">
select * from user where id = #{id};
</select>
</mapper>
测试代码:
//根据id查询用户(传递用户参数)
@Test
public void getUserById(){
SqlSession sqlSession = MybatisUtils.getSqlSession();
try{
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
User user = mapper.getUserById(1);
System.out.println(user);
}catch (Exception e){
e.printStackTrace();
}finally {
sqlSession.close();
}
}
执行结果: (由于pwd和password不对应, 输出出现问题)
解决方法:
- SQL语句中将字段 起别名
<mapper namespace="com.carson.dao.UserMapper">
<select id="getUserById" parameterType="int" resultType="user">
select id,name,pwd as password from user where id = #{id};
</select>
</mapper>
- 结果集映射
<mapper namespace="com.carson.dao.UserMapper">
<!--结果集映射 id:标识名 type:需要映射的pojo-->
<resultMap id="userMap" type="User">
<!--column:数据库中的字段 property:实体类中的属性-->
<!--不需要结果字段映射的字段不需要写result标签进行映射-->
<result column="pwd" property="password"></result>
</resultMap>
<select id="getUserById" parameterType="int" resultMap="userMap">
select * from user where id = #{id};
</select>
</mapper>
然后在使用它的语句中使用resultMap属性就可以了(注意去掉了 resultType属性)
<select id="getUserById" parameterType="int" resultMap="userMap">
select * from user where id = #{id};
</select>
2. 结果集映射
- resultMap元素是Mybatis中最重要最强大的标签元素
- 默认情况下,MyBatis 会在幕后自动创建一个
ResultMap
,再根据属性名来映射列到 JavaBean 的属性上。 - ResultMap的设计思想: 对于简单的语句根本不需要配置显式的结果映射,而对于复杂一点的语句只需要描述它们的关系就行了。
- ResultMap最优秀的地方在于,虽然你已经对于它相当了解,但是根本不需要显式地用到它们。
- 更多内容可参考:官方文档
日志
1.日志工厂
如果一个数据库操作,出现了错误,需要排查的话。日志就是最好的工具。
以前排查的方式: print打印输出 或 debug
现在排查的方式: 日志工厂
- LOG4J 【重点掌握】
- STDOUT_LOGGING 【重点掌握】
- SLF4J
- JDK_LOGGING
- COMMONS_LOGGING
- NO_LOGGING
在Mybatis中具体使用哪一个日志实现,在mybatis的核心设置文件中的setting标签进行设置。
以在mybaits的核心配置文件中配置 STDOUT_LOGGING(标准日志输出)为例:
<!--设置日志工厂-->
<settings>
<!--标准的日志工厂的实现 注意字符串中不能含有空格-->
<setting name="logImpl" value="STDOUT_LOGGING"/>
</settings>
2.LOG4J
什么是LOG4J ?
-
Log4j是一个 外部的类, 故使用Log4j需要导包。
-
Log4j是Apache的一个开源项目,通过使用Log4j,我们可以控制日志信息输送的目的地是控制台、文件、GUI组件等。
-
可以控制每一条日志的输出格式;
-
通过定义每条日志信息的级别,我们能够细致地控制日志的生成过程。
-
可以通过一个配置文件来灵活地进行配置,而不需要修改应用的代码。
使用准备:
- 先导入Log4j的包:
<dependencies>
<!--引入LOG4J日志依赖-->
<!-- https://mvnrepository.com/artifact/log4j/log4j -->
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.17</version>
</dependency>
</dependencies>
- 编写配置文件,即 log4j.properties:
由于Log4j可以控制日志信息输送的目的地是/控制台(console)/文件(file)/GUI组件等; 这里以日志输出到console和file的配置文件为例 :
#将等级为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/carson.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
#日志输出级别(设置DEBUG等级才输出)
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
- 配置log4j为日志的实现
<!--设置日志工厂-->
<settings>
<!--配置LOG4J为日志的实现 注意字符串不能有空格-->
<setting name="logImpl" value="LOG4J"/>
</settings>
- 运行测试代码:
LOG4J的简单使用:
-
在要使用LOG4J的类中,导入包
即: import org.apache.log4j.Logger
-
实例化日志对象,参数为: 当前类的class
//实例化日志对象,Logger.getLogger的参数为 当前类的class
static Logger logger = Logger.getLogger(UserDaoTest.class);
- 运行测试代码:
package com.carson.dao;
import com.carson.pojo.User;
import com.carson.utils.MybatisUtils;
import org.apache.ibatis.session.SqlSession;
import org.apache.log4j.Logger;
import org.junit.Test;
public class UserDaoTest {
//实例化日志对象
static Logger logger = Logger.getLogger(UserDaoTest.class);
/*测试log4j日志的方法*/
@Test
public void log4jTest(){
logger.info("info:进入了Log4j的测试方法");
logger.debug("debug:进入了Log4j的测试方法");
logger.error("error:进入了Log4j的测试方法");
}
}
日志级别(类别):
即 每条日志信息的级别(如: **debug/error/info **等级别)
我们能够细致地控制日志的生成过程,即可以控制输出不同级别的日志信息。
logger.info("info:进入了Log4j的测试方法");
logger.debug("debug:进入了Log4j的测试方法");
logger.error("error:进入了Log4j的测试方法");
分页
为什么要分页? -----> 减少数据的处理量
使用Limit分页
语法: SELECT * FROM user limit startIndex,pageSize;
select * from user limit 3; #一个参数即[0,n]
在mybatis中使用limit进行分页 :
- 接口
//limit实现分页
public List<User> getUserByLimit(Map<String,Integer> map);
- Mapper.xml
<!--limit实现分页-->
<select id="getUserByLimit" parameterType="map" resultMap="userMap">
select * from user limit #{startIndex},#{pageSize};
</select>
- 测试
//limit分页测试方法
@Test
public void getUserByLimit(){
SqlSession sqlSession = MybatisUtils.getSqlSession();
try{
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
//构建map
HashMap<String, Integer> map = new HashMap<String, Integer>();
map.put("startIndex",1);
map.put("pageSize",4);
List<User> userList = mapper.getUserByLimit(map);
for (User user : userList) {
System.out.println(user);
}
}catch(Exception e){
e.printStackTrace();
}finally{
sqlSession.close();
}
}
RowBounds分页
不再使用SQL实现分页。
- 接口:
//RowBounds实现分页
public List<User> getUserByRowBounds();
- Mapper.xml
<!--RowBounds实现分页-->
<select id="getUserByRowBounds" resultMap="userMap">
select * from user;
</select>
- 测试:
//RowBounds实现分页
@Test
public void getUserByRowBounds(){
SqlSession sqlSession = MybatisUtils.getSqlSession();
//RowBounds实现
RowBounds rowBounds = new RowBounds(1, 4);
//通过java代码层面实现分页
List<User> userList = sqlSession.selectList("com.carson.dao.UserMapper.getUserByRowBounds", null, rowBounds);
for (User user : userList) {
System.out.println(user);
}
sqlSession.close();
}
分页插件实现分页
那么mybatis的插件作用在哪一环节呢?它主要作用在Executor执行器与mappedeStatement之间,也就是说mybatis可以在插件中获得要执行的sql语句,在sql语句中添加limit语句,然后再去对sql进行封装,从而可以实现分页处理。
搞清楚了分页插件的执行情况,下面来总结下mybatis中PageHelper的使用!!
引入PageHelper的jar包
- 如果是 springboot,则可以直接引入 pagehelper-spring-boot-starter,它会帮我们省去许多不必要的配置。
<!-- https://mvnrepository.com/artifact/com.github.pagehelper/pagehelper-spring-boot-starter -->
<dependency>
<groupId>com.github.pagehelper</groupId>
<artifactId>pagehelper-spring-boot-starter</artifactId>
<version>1.2.12</version>
</dependency>
- 如果是普通的 springmvc 类的项目,则引入 pageHelper 即可。
<dependency>
<groupId>com.github.pagehelper</groupId>
<artifactId>pagehelper</artifactId>
<version>4.1.4</version>
</dependency>
pagehelper插件配置
- 如果是 springboot,则直接配置几个配置项即可:
# mybatis 相关配置
mybatis:
#... 其他配置信息
configuration-properties:
helperDialect: mysql
offsetAsPageNum: true
rowBoundsWithCount: true
reasonable: true
mapper-locations: mybatis/mapper/*.xml
- 如果是普通 springmvc 项目,则需要配置mybaits核心配置文件:
<?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>
<plugins>
<plugin interceptor="com.github.pagehelper.PageInterceptor">
<!-- 该参数指明要连接的是哪个数据库 -->
<property name="helperDialect" value="mysql"/>
<!-- 该参数默认为false -->
<!-- 设置为true时,会将RowBounds第一个参数offset当成pageNum页码使用 -->
<!-- 和startPage中的pageNum效果一样-->
<property name="offsetAsPageNum" value="true"/>
<!-- 该参数默认为false -->
<!-- 设置为true时,使用RowBounds分页会进行count查询 -->
<property name="rowBoundsWithCount" value="true"/>
<!-- 设置为true时,如果pageSize=0或者RowBounds.limit = 0就会查询出全部的结果 -->
<!-- (相当于没有执行分页查询,但是返回结果仍然是Page类型)-->
<property name="pageSizeZero" value="true"/>
<!-- 3.3.0版本可用 - 分页参数合理化,默认false禁用 -->
<!-- 启用合理化时,如果pageNum<1会查询第一页,如果pageNum>pages会查询最后一页 -->
<!-- 禁用合理化时,如果pageNum<1或pageNum>pages会返回空数据 -->
<property name="reasonable" value="true"/>
<!-- 3.5.0版本可用 - 为了支持startPage(Object params)方法 -->
<!-- 增加了一个`params`参数来配置参数映射,用于从Map或ServletRequest中取值 -->
<!-- 可以配置pageNum,pageSize,count,pageSizeZero,reasonable,orderBy,不配置映射的用默认值 -->
<!-- 不理解该含义的前提下,不要随便复制该配置 -->
<property name="params" value="pageNum=start;pageSize=limit;"/>
<!-- 支持通过Mapper接口参数来传递分页参数 -->
<property name="supportMethodsArguments" value="true"/>
<!-- always总是返回PageInfo类型,check检查返回类型是否为PageInfo,none返回Page -->
<property name="returnPageInfo" value="check"/>
</plugin>
</plugins>
</configuration>
使用:在执行sql前添加语句,完成分页功能
在查询的sql语句执行之前,添加一行代码
PageHelper.startPage(1, 10);
第一个参数表示第几页,第二个参数表示每页显示的记录数。
这样在执行sql后就会将记录按照语句中设置的那样进行分页。
如果需要获取总记录数的话,需要
PageInfo类的对象,这个对象可以获取总记录数
下面看下测试的代码。
public class Test01 {
@Test
public void selectPaging() throws Exception{
//1.加载核心配置文件
InputStream is = Resources.getResourceAsStream("MyBatisConfig.xml");
//2.获取SqlSession工厂对象
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(is);
//3.通过工厂对象获取SqlSession对象
SqlSession sqlSession = sqlSessionFactory.openSession(true);
//4.获取StudentMapper接口的实现类对象
StudentMapper mapper = sqlSession.getMapper(StudentMapper.class);
//通过分页助手来实现分页功能
// 第一页:显示3条数据
//PageHelper.startPage(1,3);
// 第二页:显示3条数据
//PageHelper.startPage(2,3);
// 第三页:显示3条数据
PageHelper.startPage(3,3);
//5.调用实现类的方法,接收结果
List<Student> list = mapper.selectAll();
//6.处理结果
for (Student student : list) {
System.out.println(student);
}
//获取分页相关参数
PageInfo<Student> info = new PageInfo<>(list);
System.out.println("总条数:" + info.getTotal());
System.out.println("总页数:" + info.getPages());
System.out.println("当前页:" + info.getPageNum());
System.out.println("每页显示条数:" + info.getPageSize());
System.out.println("上一页:" + info.getPrePage());
System.out.println("下一页:" + info.getNextPage());
System.out.println("是否是第一页:" + info.isIsFirstPage());
System.out.println("是否是最后一页:" + info.isIsLastPage());
//7.释放资源
sqlSession.close();
is.close();
}
}
- 通过
PageInfo对象
获取分页插件的相关参数获取:
这个对象的核心方法如下:
- long getTotal() 获取总条数
- int getPages() 获取总页数
- int getPageNum() 获取当前页
- int getPageSize() 获取每页显示条数
- int getPrePage() 获取上一页
- int getNextPage() 获取下一页
- boolean islsFirstPage() 获取是否是第一页
- boolean islsLastPage() 获取是否是最后一页
总结:
这个PageHelper其实也有缺点,因为它对逆向工程生成代码支持不好,不能对有查询条件的查询分页,会异常,上面是无条件查询。
当然,我们自己可以修改这个PageHelper插件,使其支持条件查询,当然,我是修改不了的……网上有修改过后的PageHelper插件,可以支持条件查询,相对来说就比较强大了,可以在自己的工程中依赖修改过后的分页插件进行开发。
Mybatis的逆向工程
参考学习链接:Mybatis-逆向工程
使用注解开发
- 注解在接口上实现:
public interface UserMapper {
//使用注解查询全部用户
@Select("select * from user")
public List<User> getUsers();
}
- 在Mybatis的核心配置文件中绑定接口
<!--绑定接口-->
<mappers>
<mapper class="com.carson.dao.UserMapper"/>
</mappers>
- 编写测试代码:
@Test
public void test(){
SqlSession sqlSession = MybatisUtils.getSqlSession();
try{
//底层主要应用 反射
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
List<User> users = mapper.getUsers();
for (User user : users) {
System.out.println(user);
}
}catch (Exception e){
e.printStackTrace();
}finally{
sqlSession.close();
}
}
注意:
-
使用注解不需要编写接口相应的xml文件。
-
本质: 反射机制实现
-
使用注解来映射简单语句会使代码更简洁。然而对于复杂的语句,Java注解就力不从心了,并且会显得更加混乱。
-
因此,如果需要完成复杂的事情,最好使用XML来映射语句。
Mybatis执行流程
CRUD
- 可以在工具类创建的时候设置自动提交事务。(事务由驱动程序管理)
//true设置为自动提交事务
public static SqlSession getSqlSession(){
return sqlSessionFactory.openSession(true);
}
- 编写接口,增加注解
public interface UserMapper {
//使用注解查询全部用户
@Select("select * from user")
public List<User> getUsers();
//使用注解查询特点id用户(简单数据类型需要@Param)
@Select("select * from user where id = #{id}")
public User getUserById(@Param("id") int id);
//注解增加用户(复杂数据类型不用@Param)
@Insert("insert into user values(#{id},#{name},#{password})")
public int addUser(User user);
//注解更新一个用户信息
@Update("update user set name=#{name},pwd=#{password} where id=#{id}")
public int updateUser(User user);
//注解根据id删除一个用户(简单数据类型需要@Param)
@Delete("delete from user where id=#{uid}")
public int delUser(@Param("uid")int id);
}
- 注意在核心配置文件中绑定接口
<!--绑定接口-->
<mappers>
<mapper class="com.carson.dao.UserMapper"/>
</mappers>
- 编写测试代码测试即可。
关于@Param注解:
- 基本类型的参数或者String类型,需要在形参前面加上这个注解。
- 引用类型的数据不用加这个注解。
- 如果只有一个基本类型形参的话,可以忽略不写,但建议写上。
- 我们在SQL中引用的就是我们这里的@Param中设定的属性名。
Lombok
- java library plugin
- build tools
- with one annotation your class
- 再也不用手写一些Getter和Setter方法,加一个注解即可实现。
- 即 偷懒用的插件。
使用步骤:
- 在IDEA中搜索并安装Lombok插件
- 在项目中导入Lombok的jar包
<!-- https://mvnrepository.com/artifact/org.projectlombok/lombok -->
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.18.20</version>
</dependency>
- 在实体类上加注解即可。
@Data
@AllArgsConstructor
@NoArgsConstructor
......
多对一处理
- 多个学生对象对应一个老师对象
- 对于学生这边,多个学生 关联 一个老师。【多对一】
- 对于老师这边,一个老师 有 很多的学生。【一对多】
测试环境搭建
- 创建相应的数据库表和字段:(其中学生表的tid字段参照老师表的id字段)
- 新建实体类
public class Teacher {
private int id;
private String name;
.......
}
public class Student {
private int id;
private String name;
//由于数据表间字段有外键关联关系
//实体类也需要进行关联,保持数据安全和干净
//故学生需要关联一个老师对象
private Teacher teacher;
......
}
- 建立Mapper接口
public interface TeacherMapper {
//简单sql用注解,复杂sql用xml配置文件
//使用简单的注解查询特定id的老师
@Select("select * from teacher where id=#{tid}")
public Teacher getTeacherById(@Param("tid")int id);
}
public interface StudentMapper {
}
- 建立接口对应的Mapper.xml文件
- 在核心配置文件中绑定Mapper接口或者xml文件【方法很多,随心选】
<!--核心配置文件绑定接口-->
<mappers>
<mapper class="com.carson.dao.TeacherMapper"/>
<mapper class="com.carson.dao.StudentMapper"/>
</mappers>
- 编写测试代码进行测试。
按照查询嵌套处理
特点: SQL简单,标签书写复杂。(类似SQL中的子查询)
<!--查询所有学生的信息及相应的老师信息
思路:(SQL嵌套查询的思路)书写三个标签
1 查询所有学生的信息
2 根据查询出来的学生tid信息,查询对应的老师信息-->
<select id="getStudents" resultMap="StudentMap">
select * from student
</select>
<resultMap id="StudentMap" type="Student">
<result property="id" column="id"/>
<result property="name" column="name"/>
<!--复杂的属性,我们需要单独处理
对象: association 集合: collection
这里javaType指明对象的类型, select属性相当于嵌套了一个查询语句
-->
<association property="teacher" column="tid" javaType="Teacher" select="getTeachers" />
</resultMap>
<select id="getTeachers" resultType="Teacher">
select * from teacher
</select>
按照结果嵌套处理(推荐)
特点: SQL复杂,标签书写简单。(类似SQL中的联表查询)
<!--按照结果嵌套查询-->
<select id="getStudents2" resultMap="StudentMap2">
select s.id sid,s.name sname,t.name tname from student s,teacher t where s.tid = t.id
</select>
<resultMap id="StudentMap2" type="Student">
<result property="name" column="sname" />
<result property="id" column="sid"/>
<!--复杂对象单独处理,对象:association 集合:collection-->
<association property="teacher" javaType="Teacher">
<result property="name" column="tname"/>
</association>
</resultMap>
一对多处理
比如: 一个老师拥有多个学生!
对于老师而言,就是一对多的关系!
测试环境搭建
-
数据库表和字段同上。
-
实体类
public class Student {
private int id;
private String name;
private int tid;
......
}
public class Teacher {
private int id;
private String name;
//一个老师有多个学生
private List<Student> students;
......
}
- 建立Mapper接口
public interface TeacherMapper {
//测试获取所有的老师
public List<Teacher> getTeacher();
}
- 建立接口对应的Mapper.xml文件
<!--namespace指明实现的接口-->
<mapper namespace="com.carson.dao.TeacherMapper">
<!--测试获取所有老师-->
<select id="getTeacher" resultType="Teacher">
select * from teacher
</select>
</mapper>
- 在核心配置文件中绑定Mapper接口或者xml文件【方法很多,随心选】
<!--核心配置文件绑定接口-->
<mappers>
<mapper class="com.carson.dao.TeacherMapper"/>
<mapper class="com.carson.dao.StudentMapper"/>
</mappers>
- 编写测试代码进行测试。
按照查询嵌套处理:
<!--按照查询嵌套处理-->
<select id="getTeacher2" resultMap="TeacherMap2">
select * from teacher
</select>
<resultMap id="TeacherMap2" type="Teacher">
<result property="id" column="id"/>
<result property="name" column="name"/>
<!--复杂的对象,需要单独处理,对象:association 集合:collection
javaType: 指定属性的类型
ofType: 代表集合中的泛型信息-->
<collection property="students" javaType="ArrayList" ofType="Student" column="id" select="getStudent"/>
</resultMap>
<select id="getStudent" resultType="Student">
select * from student where tid=#{tid}
</select>
按照结果嵌套处理(推荐)
<!--按结果嵌套查询-->
<select id="getTeacher" resultMap="TeacherMap">
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="TeacherMap" 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>
小结:
-
关联: association 【多对一】
-
集合: collection 【一对多】
-
关于javaType 和 ofType
- javaType 用来指定实体类中属性的类型
- ofType 用来指定映射到集合中的pojo类型,即泛型中的约束类型
注意点:
- 保证SQL的可读性,尽量保证通俗易懂
- 注意 一对多 和 多对一,属性名和字段的问题。
- 按照查询嵌套处理
- 按照结果嵌套处理**(推荐)**
动态SQL
什么是动态SQL:动态SQL就是指根据的不同的条件生成不同的SQL语句。
动态SQL的本质: 本质还是SQL语句,只是可以在SQL层面执行逻辑代码。
如果用过 JSTL 或任何基于类 XML 语言的文本处理器,对动态 SQL 元素可能会感觉似曾相识。MyBatis 之前的版本中,需要花时间了解大量的元素。
MyBatis 3 替换了之前的大部分元素,精简了元素种类,现在要学习的元素种类比原来的一半还要少。
- if
- choose (when, otherwise)
- trim (where, set)
- foreach
测试环境搭建
需要用到的数据库表:
需要用到的 生成UUID的工具类:
package com.carson.utils;
import org.junit.Test;
import java.util.UUID;
//镇压警告
@SuppressWarnings("all")
public class IDutils {
public static String getId(){
//创建UUID作为记录id进行返回,确保每条记录的唯一性
return UUID.randomUUID().toString().replaceAll("-","");
}
//测试UUID能否正确生成
@Test
public void test(){
System.out.println(IDutils.getId());
System.out.println(IDutils.getId());
System.out.println(IDutils.getId());
}
}
创建一个maven基础工程:
- maven的pom.xml中增加资源导出配置:
<!--新建maven项目,加上以下资源导出配置,防止资源导出失败-->
<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/com/carson/dao</directory>
<includes>
<include>**/*.properties</include>
<include>**/*.xml</include>
</includes>
<filtering>true</filtering>
</resource>
</resources>
</build>
- 编写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核心配置文件-->
<configuration>
<!--引入外部的配置文件-->
<!--由于配置文件在resources资源目录下,故文件路径不需要写全路径-->
<properties resource="db.properties"/>
<!--设置日志工厂-->
<settings>
<!--配置为标准日志输出-->
<setting name="logImpl" value="STDOUT_LOGGING"/>
<!--是否开启驼峰命名自动映射
即从经典数据库列名 A_COLUMN 映射到经典 Java 属性名 aColumn
-->
<setting name="mapUnderscoreToCamelCase" value="true"/>
</settings>
<!--可以给实体类起别名 标签顺序是有要求的-->
<typeAliases>
<!--通过扫描实体类所在的包,它的默认别名 就为 这个类的类名的小写-->
<!--这里的包下的类是User, 则默认别名为:user-->
<package name="com.carson.pojo" />
</typeAliases>
<environments default="development">
<environment id="development">
<transactionManager type="JDBC"/><!--事务管理JDBC-->
<dataSource type="POOLED">
<!--value值直接读取配置文件 ${变量名}的方式-->
<property name="driver" value="${driver}"/>
<property name="url" value="${url}"/>
<property name="username" value="${username}"/>
<property name="password" value="${password}"/>
</dataSource>
</environment>
</environments>
<!--核心配置文件绑定接口-->
<mappers>
<mapper class="com.carson.dao.BlogMapper"/>
</mappers>
</configuration>
- 编写实体类
package com.carson.pojo;
import java.util.Date;
public class Blog {
private String id;
private String title;
private String author;
private Date createTime;//属性名和数据字段不一致,在核心配置文件中开启驼峰映射
private int views;
public Blog() {
}
public Blog(String id, String title, String author, Date createTime, int views) {
this.id = id;
this.title = title;
this.author = author;
this.createTime = createTime;
this.views = views;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getAuthor() {
return author;
}
public void setAuthor(String author) {
this.author = author;
}
public Date getCreateTime() {
return createTime;
}
public void setCreateTime(Date createTime) {
this.createTime = createTime;
}
public int getViews() {
return views;
}
public void setViews(int views) {
this.views = views;
}
@Override
public String toString() {
return "Blog{" +
"id='" + id + '\'' +
", title='" + title + '\'' +
", author='" + author + '\'' +
", createTime=" + createTime +
", views=" + views +
'}';
}
}
- 编写实体类对应的Mapper接口和Mapper.xml文件
public interface BlogMapper {
//插入数据
public int addBlog(Blog blog);
}
<mapper namespace="com.carson.dao.BlogMapper">
<!--插入数据-->
<insert id="addBlog" parameterType="Blog">
insert into blog values(#{id},#{title},#{author},#{createTime},#{views})
</insert>
</mapper>
- 编写测试代码 来插入数据
public class DaoTest {
//测试插入数据
public static void main(String[] args) {
SqlSession sqlSession = MybatisUtils.getSqlSession();
try{
BlogMapper mapper = sqlSession.getMapper(BlogMapper.class);
//create a blog object
Blog blog = new Blog();
blog.setId(IDutils.getId());//ID设置为UUID,确保唯一性
blog.setTitle("Mybatis如此easy!");
blog.setAuthor("Carson");
blog.setCreateTime(new Date());
blog.setViews(9999);
int affectedRows = mapper.addBlog(blog);
if(affectedRows>0){
System.out.println("插入数据成功");
}
blog.setId(IDutils.getId());
blog.setViews(1000);
blog.setTitle("JAVA如此easy!");
affectedRows = mapper.addBlog(blog);
if(affectedRows>0){
System.out.println("插入数据成功");
}
blog.setId(IDutils.getId());
blog.setViews(9999);
blog.setTitle("Spring如此easy!");
affectedRows = mapper.addBlog(blog);
if(affectedRows>0){
System.out.println("插入数据成功");
}
blog.setId(IDutils.getId());
blog.setViews(9999);
blog.setTitle("微服务如此easy!");
affectedRows = mapper.addBlog(blog);
if(affectedRows>0){
System.out.println("插入数据成功");
}
}catch (Exception e){
e.printStackTrace();
}finally {
sqlSession.close();
}
}
}
故 利用Java脚本也可以实现SQL脚本的数据分享。
动态SQL之IF语句
需求: 方法传入参数时返回特定记录,不传入数据时则返回所有记录
解决方法:
方法一: 接口中重写多个方法(即有输入参数的方法和没有输入参数的方法)
方法二: 利用动态SQL的IF语句解决。(test属性对应一个语句表达式)
- 动态SQL通常要做的事情是根据条件决定是否给where子句增加一部分条件
- 编写Mapper接口方法:
//动态SQL之IF语句实现查询博客记录
public List<Blog> queryBlogIF(Map map);
- 编写接口对应的Mapper.xml文件:
<!--动态SQL之IF语句实现查询博客记录-->
<select id="queryBlogIF" parameterType="map" resultType="blog">
select * from blog where 1=1
<if test="title != null">
and title = #{title}
</if>
<if test="author != null">
and author = #{author}
</if>
</select>
- 编写测试代码:
//动态SQL查询博客记录
@Test
public void queryBlogIF(){
SqlSession sqlSession = MybatisUtils.getSqlSession();
try{
BlogMapper mapper = sqlSession.getMapper(BlogMapper.class);
Map map = new HashMap();
//map.put("title","Mybatis如此easy!");
//map.put("author","Carson");
List<Blog> blogs = mapper.queryBlogIF(map);
for (Blog blog : blogs) {
System.out.println(blog);
}
}catch (Exception e){
e.printStackTrace();
}finally {
sqlSession.close();
}
}
动态SQL之 trim (where, set)
where
-
当不使用where标签遇到的问题
-
<select id="queryBlogIF" resultType="blog"> SELECT * FROM blog WHERE <if test="state != null"> state = #{state} </if> <if test="title != null"> AND title like #{title} </if> </select>
-
如果没有匹配的条件会怎么样?最终这条 SQL 会变成这样:(查询失败)
-
SELECT * FROM blog WHERE
-
如果匹配的只是第二个条件又会怎样?这条 SQL 会是这样:(查询失败)
-
SELECT * FROM blog WHERE AND title like ‘someTitle’
-
使用where标签后
-
where 元素只会在子元素返回内容的情况下才插入 “WHERE” 子句。而且,若where的子元素的开头为 “AND” 或 “OR”,where 元素也会将它们去除。
-
<!--动态SQL之where标签实现查询博客记录--> <select id="queryBlogWhere" parameterType="map" resultType="blog"> select * from blog <where> <if test="title != null"> title = #{title} </if> <if test="author != null"> and author = #{author} </if> </where> </select>
-
当匹配第一个条件时,最终这条 SQL 会变成这样:
-
select * from blog WHERE title = ?
-
当匹配第二个条件时,其会自动将and去掉,故最终这条 SQL 会变成这样:
-
select * from blog WHERE author = ?
-
当匹配第一二个条件都不符合时,不会插入where子句, SQL 会变成这样:
-
select * from blog
-
通过自定义 trim 元素来定制 where 元素的功能
-
和 where 元素等价的自定义 trim 元素为:
-
<trim prefix="WHERE" prefixOverrides="AND |OR "> ... </trim>
-
prefixOverrides 属性会忽略通过管道符分隔的文本序列(注意prefixOverrides中的空格是必要的)。上述例子会移除所有 prefixOverrides 属性中指定的内容,并且插入 prefix 属性中指定的内容。
-
故上面sql的等价形式为:
-
<select id="queryBlogWhere" parameterType="map" resultType="blog"> select * from blog <trim prefix="where" prefixOverrides="AND | OR"> <if test="title != null"> title = #{title} </if> <if test="author != null"> and author = #{author} </if> </trim> </select>
-
SET
-
用于动态更新的SQL语句的类似解决方案叫做 set标签。set 元素可以用于动态包含需要更新的列,忽略其它不更新的列。set 元素会动态地在行首插入 SET 关键字,并会删掉额外的逗号。比如:
-
<!--动态SQL之SET实现修改博客记录--> <update id="updateBlogBySet" 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语句为:
-
update blog SET title = ?, author = ? where id = ?
-
当第一个条件满足时,会自动去掉逗号,故输出的sql语句为:
-
update blog SET title = ? where id = ?
-
-
与 set 元素等价的自定义 trim 元素
-
覆盖了后缀值设置,并且自定义了前缀值。
-
<trim prefix="SET" suffixOverrides=","> ... </trim>
-
故上面sql的等价形式为:
-
<update id="updateBlogBySet" parameterType="map"> update blog <trim prefix="SET" suffixOverrides=","> <if test="title != null"> title = #{title}, </if> <if test="author != null"> author = #{author}, </if> </trim> where id = #{id} </update>
-
动态SQL之 choose (when, otherwise)
有时候,我们不想使用所有的条件,而只是想从多个条件中选择一个使用。针对这种情况,MyBatis 提供了 choose 元素,它有点像 Java 中的 switch 语句。
-
<!--动态SQL之choose,when,otherwise实现查询博客记录--> <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>
-
当三个参数都存在时,**选择第一个执行,**输出的sql为:
-
select * from blog WHERE title = ?
-
当只有第三个参数存在时,只会走默认情况,输出的sql为:
-
select * from blog WHERE views = ?
-
即choose会按从上到下的顺序插入一个符合情况的语句
-
SQL片段
有的时候,我们可能会将一些共同功能的代码部分抽取出来,方便复用!
- 使用sql标签抽取公共的部分。
<!--抽取SQL片段实现查询博客记录-->
<sql id="if-title-author">
<if test="title != null">
title = #{title}
</if>
<if test="author != null">
and author = #{author}
</if>
</sql>
- 在需要使用的地方使用include标签引用即可。
<!--SQL片段测试-->
<select id="queryBlogBySql" parameterType="map" resultType="blog">
select * from blog
<where>
<include refid="if-title-author"></include>
</where>
</select>
注意事项:
- 最好是基于单表来定义SQL片段!
- 抽取的共同代码中不要包含where标签!因为会限制扩展性!
动态SQL之 foreach
动态 SQL 一个常见使用场景是对集合进行遍历(尤其是在构建 IN 条件语句时)。
- 编写接口方法:
//动态SQL之foreach实现查询博客记录
public List<Blog> queryBlogForeach(Map map);
- 编写接口配置文件:
<!--动态SQL之foreach实现查询博客记录
collection:对应集合名
open:对应开始符号
close:对应结束符号
seperator:对应分隔符
index:对应迭代的序号
item:对应迭代的具体值
-->
<select id="queryBlogForeach" parameterType="map" resultType="blog">
select * from blog
<where>
id in
<foreach collection="ids" open="(" close=")" separator="," item="id">
#{id}
</foreach>
</where>
</select>
对应输出的sql为:
select * from blog WHERE id in ( ? , ? , ? )
- 编写测试代码:
//queryBlogForeach
@Test
public void queryBlogForeach(){
SqlSession sqlSession = MybatisUtils.getSqlSession();
try{
BlogMapper mapper = sqlSession.getMapper(BlogMapper.class);
//定义一个集合,并添加数据
ArrayList<String> ids = new ArrayList<String>();
ids.add("58ee7492a6974aafa6a7712226d57188");
ids.add("6a1900626bd149bc98e48f246e2e21fb");
ids.add("b56e45facb67420e84c275cf0f39e043");
//万能的map
Map map = new HashMap();
map.put("ids",ids);//键名ids,值对应集合ids
List<Blog> blogs = mapper.queryBlogForeach(map);
for (Blog blog : blogs) {
System.out.println(blog);
}
}catch (Exception e){
e.printStackTrace();
}finally {
sqlSession.close();
}
}
小结
- 动态SQL就是在拼接SQL语句,我们只要保证SQL的正确性,按照SQL的格式,去排列组合即可。
- 先在mysql控制台写出完整的sql验证sql的正确性,再对应的去拼接动态SQL即可
缓存(了解)
简介
-
什么是缓存(Cache)?
- 存在内存 中的临时数据。
- 缓存指的就是 查询缓存。
- 将被用户经常查询的数据放在缓存(内存)中,用户去查询数据就不用从磁盘上(关系型数据库数据文件)查询,而是从缓存中查询,从而提高查询效率,解决了高并发系统的性能问题【读写分离,主从复制】
-
为什么使用缓存?
- 减少和数据库的交互次数,减少系统开销,提高系统效率。
- 查询相同数据的时候,直接走缓存,不用走数据库了。
- 提高查询效率。
-
什么样的数据适合缓存? 什么样的数据不适合缓存?
- 经常查询并且不经常改变的数据【适合缓存】
- 不经常查询并且经常改变的数据【不适合缓存】
Mybatis缓存
- Mybatis包含一个非常强大的查询缓存特性,它可以非常方便地定制和配置缓存
- 使用缓存可以极大的提升查询效率。
- Mybatis中默认定义了两级缓存: 一级缓存和二级缓存。
- 默认情况下,只有一级缓存开启。(SqlSession级别的缓存,也称为本地缓存)
- 二级缓存需要手动开启和配置。(基于namespace级别的缓存)
- 为了提高扩展性,Mybatis定义了缓存接口Cache,可以通过实现Cache接口来自定义二级缓存。
一级缓存
-
一级缓存也叫本地缓存。
- 默认情况下 开启。
- 与数据库同一次会话期间查询到的数据会放在本地缓存中。
- 以后如果需要获取相同的数据,直接从缓存中拿,没必须再去查询数据库。
- 映射语句文件中的所有 select 语句的结果将会被缓存。
- 映射语句文件中的所有 insert、update 和 delete 语句会刷新缓存。
- 缓存会使用最近最少使用算法(LRU, Least Recently Used)算法来清除不需要的缓存。
- 缓存不会定时进行刷新(也就是说,没有刷新间隔)。
-
一级查询缓存测试:
- 开启日志。(方便查看输出信息)
<!--配置为标准日志输出-->
<setting name="logImpl" value="STDOUT_LOGGING"/>
- 测试在一个sqlSession中查询两次相同记录。
SqlSession sqlSession = MybatisUtils.getSqlSession();
try{
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
//查询同一个用户信息
User user = mapper.queryUserByID(1);
System.out.println(user);
System.out.println("===============================");
//查询同一个用户信息
User user1 = mapper.queryUserByID(1);
System.out.println(user1);
System.out.println(user==user1);
}catch(Exception e){
e.printStackTrace();
}finally {
sqlSession.close();
}
- 查看日志输出 (只执行了一个sql语句,表明第二次查询的内容是从缓存中获得的)
-
一级 刷新缓存测试(增删改操作会刷新缓存)
- 测试在查询两次相同记录中间加入更新操作:
SqlSession sqlSession = MybatisUtils.getSqlSession(); try{ UserMapper mapper = sqlSession.getMapper(UserMapper.class); //查询同一个用户信息 User user = mapper.queryUserByID(1); System.out.println(user); //测试 中间更新一个用户信息 int affectedRows = mapper.updateUser(new User(3,"lin","08080808")); if(affectedRows > 0){ System.out.println("User Update Successfully!"); } System.out.println("==============================="); //查询同一个用户信息 User user1 = mapper.queryUserByID(1); System.out.println(user1); System.out.println(user==user1); }catch(Exception e){ e.printStackTrace(); }finally { sqlSession.close(); }
- 查看日志输出 (由于加入了update语句,会更新缓存,故两次查询同个记录都会从数据库中查数据)
一级缓存失效的情况:
- 查询不同的记录。
- 增删改操作,可能会改变原来的数据,所以必定会刷新缓存!
- 查询不同的Mapper.xml文件。
- 手动清理缓存。
//手动请理缓存
sqlSession.clearCache();
小结:
- 一级缓存是默认开启的,只在一次sqlSession中有效,也就是拿到连接到关闭连接这个区间。
- 一级缓存本质就是个Map。
二级缓存
- 二级缓存也叫全局缓存,一级缓存的作用域太低,所以诞生了二级缓存。
- 二级缓存是基于namespace级别的缓存,即一个名称空间,对应一个二级缓存。
- 工作机制:
- 一个会话查询一条数据,这个数据就会被放在当前会话的一级缓存中;
- 如果当前会话关闭了,这个会话对应的一级缓存就没了;但我们想要的是,会话关闭了,一级缓存中的数据被保存到二级缓存中;
- 新的会话查询信息,就可以从二级缓存中获取内容。
- 不同的mapper接口查出的数据会放在自己对应的缓存(map)中。
步骤:
- 显式开启全局缓存:
<!--显式地开启全局缓存(默认全局缓存是开启的)-->
<setting name="cacheEnabled" value="true"/>
- 要启用全局的二级缓存,只需要在Mapper配置文件中添加一行:
<cache/>
也可以自定义参数:
<cache
eviction="FIFO"
flushInterval="60000"
size="512"
readOnly="true"/>
- 测试。
//创建两个sqlSession
SqlSession sqlSession = MybatisUtils.getSqlSession();
SqlSession sqlSession2 = MybatisUtils.getSqlSession();
//对应创建两个mapper
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
UserMapper mapper2 = sqlSession2.getMapper(UserMapper.class);
//sqlsession执行方法
User user = mapper.queryUserByID(1);
System.out.println(user);
sqlSession.close();
//sqlSession2执行方法
User user2 = mapper2.queryUserByID(1);
System.out.println(user2);
//对象是否相同
System.out.println(user==user2);
注: 当配置时遇到问题:
Caused by: java.io.NotSerializableException: com.carson.pojo.User
两个解决办法:
- 需要对实体类进行序列化:(涉及io缓存或网络传输.即实体类需要实现Serializable接口):
public class User implements Serializable {...}
- 给添加配置属性readonly设置为true:
<!--启用全局二级缓存-->
<cache readOnly="true"/>
小结:
- 只要开启了二级缓存,在同一个Mapper下就有效。
- 所有的缓存数据都会先放在一级缓存中;
- 只有当会话关闭或者提交的时候,才会将 缓存数据提交到二级缓存中!
缓存原理
自定义缓存-ehcache
EhCache 一种广泛使用的开源Java分布式缓存,快速、精干等特点,主要面向通用缓存
知道即可, 暂且略过。工作中的缓存使用的是redis,即k-v型非关系型数据库。
The End!!创作不易,欢迎点赞/评论!!