【MyBatis】MyBatis

MyBatis简介

img

什么是MyBatis

  • MyBatis 是一款优秀的持久层框架
  • MyBatis 避免了几乎所有的 JDBC 代码和手动设置参数以及获取结果集的过程
  • MyBatis 可以使用简单的 XML 或注解来配置和映射原生信息,将接口和 Java 的 实体类 【Plain Old Java Objects,普通的 Java对象】映射成数据库中的记录。
  • MyBatis 本是apache的一个开源项目ibatis, 2010年这个项目由apache 迁移到了google code,并且改名为MyBatis 。在2013年11月迁移到Github .
  • Mybatis官方文档 : http://www.mybatis.org/mybatis-3/zh/index.html
  • GitHub : https://github.com/mybatis/mybatis-3

持久化

持久化是将程序数据在持久状态和瞬时状态间转换的机制。

  • 即把数据(如内存中的对象)保存到可永久保存的存储设备中(如磁盘)。持久化的主要应用是将内存中的对象存储在数据库中,或者存储在磁盘文件中、XML数据文件中等等。
  • JDBC就是一种持久化机制。文件IO也是一种持久化机制。

MyBatis的优点

  • 简单易学:本身就很小且简单。没有任何第三方依赖,最简单安装只要两个jar文件+配置几个sql映射文件就可以了,易于学习,易于使用,通过文档和源代码,可以比较完全的掌握它的设计思路和实现。
  • 灵活:mybatis不会对应用程序或者数据库的现有设计强加任何影响。 sql写在xml里,便于统一管理和优化。通过sql语句可以满足操作数据库的所有需求。
  • 解除sql与程序代码的耦合:通过提供DAO层,将业务逻辑和数据访问逻辑分离,使系统的设计更清晰,更易维护,更易单元测试。sql和代码的分离,提高了可维护性。
  • 提供xml标签,支持编写动态sql。

Hello MyBatis

1. maven中添加依赖

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
<dependencies>
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.5.3</version>
</dependency>

<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.47</version>
</dependency>
</dependencies>

<!-- 设置路径,保证src中的.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>

2. 配置mybatis-config.xml

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
<?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>

<!-- 引入外部资源文件 -->
<properties resource="db.properties"/>

<settings>
<!-- 开启日志 -->
<setting name="logImpl" value="STDOUT_LOGGING"/>
<!-- 将数据库字段名按照驼峰命名规定映射为实体类属性名 -->
<setting name="mapUnderscoreToCamelCase" value="true"/>
<!-- 开启二级缓存 -->
<setting name="cacheEnabled" value="true"/>
</settings>

<typeAliases>
<!-- 给某个类起别名,在mapper配置文件中可以直接使用别名 -->
<typeAlias type="com.zhao.pojo.User" alias="user"/>
<!-- 在某个包下扫描所有类,首字母小写后作为其别名 -->
<package name="com.zhao.pojo"/>
</typeAliases>

<environments default="development">
<environment id="development">
<transactionManager type="JDBC"/>
<dataSource type="POOLED">
<property name="driver" value="${driver}"/>
<property name="url" value="${url}"/>
<property name="username" value="${username}"/>
<property name="password" value="${password}"/>
</dataSource>
</environment>
</environments>

<!-- 注册mapper类 -->
<mappers>
<mapper resource="com/zhao/dao/UserMapper.xml"/>
</mappers>

</configuration>

db.properties

1
2
3
4
driver=com.mysql.jdbc.Driver
url=jdbc:mysql://localhost:3306/smbms?useUnicode=true&characterEncoding=utf8&useSSL=true
username=root
password=zhaoyuyun

注意:在MyBatis的核心配置文件xml中,配置数据库的参数时,url=xxx&amp;characterset=xxx需要带上转义符号amp; 但是如果通过db.properties中设置参数时不需要加上转义符,只需要&

3. 编写MyBatis工具类

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
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;

static {
try {
String resource = "mybatis-config.xml";
InputStream inputStream = Resources.getResourceAsStream(resource);
sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
} catch (IOException e) {
e.printStackTrace();
}
}

//获取SqlSession连接
public static SqlSession getSession(){
// 设置自动提交事务
return sqlSessionFactory.openSession(true);
}
}

4. 注册实体类

1
2
3
4
5
6
7
8
9
public class User {
private int id; //id
private String name; //姓名
private String pwd; //密码

//构造,有参,无参
//set/get
//toString()
}

5. 编写Mapper接口类

1
2
3
4
5
import com.zhao.pojo.User;
import java.util.List;
public interface UserMapper {
List<User> selectUser();
}

6. 编写Mapper.xml配置文件(配置文件中namespace中的名称为对应Mapper接口或者Dao接口的完整包名,必须一致!)

1
2
3
4
5
6
7
8
9
<?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.zhao.dao.UserMapper">
<select id="selectUser" resultType="com.zhao.pojo.User">
select * from user
</select>
</mapper>

7. 测试

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
public class MyTest {
@Test
public void selectUser() {
SqlSession session = MybatisUtils.getSession();

//方法一:
//List<User> users = session.selectList("com.zhao.mapper.UserMapper.selectUser");

//方法二:
UserMapper mapper = session.getMapper(UserMapper.class);
List<User> users = mapper.selectUser();
for (User user: users){
System.out.println(user);
}
session.close();
}
}

MyBatis CRUD

select

四种语句的通用属性:

  • id:命名空间中唯一的标识符,接口中的方法名与映射文件中的SQL语句id一一对应
  • parameterType:传入SQL语句的参数类型(可以使用万能的Map)
  • resultType:SQL语句返回值类型(完整的类名或者别名)

需求:根据id查询用户

  1. 在UserMapper中添加对应方法(可以使用@Param注解给形参名起别名)

    1
    2
    3
    4
    5
    6
    public interface UserMapper { 
    //查询全部用户
    List<User> selectUser();
    //根据id查询用户
    User selectUserById(@Param("id") int id);
    }
  2. 在UserMapper.xml中添加select语句(MyBatis会将select *返回的数据库字段名映射为pojo类对象的属性,即去对应的实体类中查找相应字段名的set方法设值【自动映射】,若属性名与数据库字段名不一致,即找不到对应的set方法,则属性值为null,此时需要使用ResultMap

    1
    2
    3
    <select id="selectUserById" resultType="com.zhao.pojo.User">
    select * from user where id = #{id}
    </select>
  3. 测试

    1
    2
    3
    4
    5
    6
    7
    8
    9
    @Test
    public void tsetSelectUserById() {
    //获取SqlSession连接
    SqlSession session = MybatisUtils.getSession();
    UserMapper mapper = session.getMapper(UserMapper.class);
    User user = mapper.selectUserById(1);
    System.out.println(user);
    session.close();
    }

insert

需求:给数据库增加一个用户

  1. 在UserMapper接口中添加对应的方法

    1
    2
    //添加一个用户
    int addUser(User user);
  2. 在UserMapper.xml中添加insert语句(传入形参是pojo时,SQL语句中的#{}会与类对象的属性变量名判断是否能够对应,不能对应的解析为null)

    1
    2
    3
    <insert id="addUser" parameterType="com.zhao.pojo.User">     
    insert into user (id,name,pwd) values (#{id},#{name},#{pwd})
    </insert>
  3. 测试

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    @Test
    public void testAddUser() {
    SqlSession session = MybatisUtils.getSession();
    UserMapper mapper = session.getMapper(UserMapper.class);
    User user = new User(5,"王五","zxcvbn");
    int i = mapper.addUser(user);
    System.out.println(i);

    // 提交事务,不写的话不会提交到数据库,除非设置sqlSessionFactory.openSession(true);
    session.commit();

    session.close();
    }

注意:增、删、改操作需要提交事务!设置方法:

  • 每次会话使用完后session.commit();
  • 或在工具类中设置sqlSessionFactory.openSession(true);

update

需求:修改用户的信息

  1. 编写接口方法

    1
    2
    //修改一个用户
    int updateUser(User user);
  2. 编写对应的配置文件SQL

    1
    2
    3
    <update id="updateUser" parameterType="com.zhao.pojo.User">
    update user set name = #{name},pwd = #{pwd} where id = #{id}
    </update>
  3. 测试

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    @Test
    public void testUpdateUser() {
    SqlSession session = MybatisUtils.getSession();
    UserMapper mapper = session.getMapper(UserMapper.class);
    User user = mapper.selectUserById(1);
    user.setPwd("123456");
    int i = mapper.updateUser(user);
    System.out.println(i);
    session.commit();
    session.close();
    }

delete

需求:根据id删除一个用户

  1. 编写接口方法

    1
    2
    //根据id删除用户
    int deleteUser(int id);
  2. 编写对应的配置文件SQL

    1
    2
    3
    <delete id="deleteUser" parameterType="int">
    delete from user where id = #{id}
    </delete>
  3. 测试

    1
    2
    3
    4
    5
    6
    7
    8
    9
    @Test
    public void testDeleteUser() {
    SqlSession session = MybatisUtils.getSession();
    UserMapper mapper = session.getMapper(UserMapper.class);
    int i = mapper.deleteUser(5);
    System.out.println(i);
    session.commit();
    session.close();
    }

传参时变量名不一致问题

当传入的形参变量名称与SQL语句中的#{}中变量名不一致时,有两种解决方案:

  1. 使用@Param注解
  • 在方法只接受一个参数的情况下,可以不使用@Param
  • 在方法接受多个参数的情况下,建议一定要使用@Param注解给参数命名。
  • 如果参数是 JavaBean , 则不能使用@Param
  • 不使用@Param注解时,参数只能有一个,并且是Javabean。
1
2
3
4
5
6
7
8
//通过密码和名字查询用户
User selectUserByNP(@Param("uname") String username, @Param("pwd") String password);

/*
<select id="selectUserByNP" resultType="com.zhao.pojo.User">
select * from user where name = #{uname} and password = #{pwd}
</select>
*/
  1. 使用万能的Map

在接口方法中,参数直接传递Map;

1
User selectUserByNP2(Map<String,Object> map);

编写SQL语句的时候,需要传递参数类型,参数类型为Map

1
2
3
<select id="selectUserByNP2" parameterType="map" resultType="com.zhao.pojo.User">
select * from user where name = #{uname} and password = #{pwd}
</select>

在使用方法的时候,Map的 key 为 sql中取的值即可,没有顺序要求!

1
2
3
4
Map<String, Object> map = new HashMap<String, Object>();
map.put("uname", "小明");
map.put("pwd", "123456");
User user = mapper.selectUserByNP2(map);

小结:

  • 所有的增删改操作都需要提交事务
  • 接口所有的普通参数,尽量都写上@Param参数,尤其是多个参数时,必须写上
  • 有时候根据业务的需求,可以考虑使用map传递参数
  • 为了规范操作,在SQL的配置文件中,尽量将Parameter参数和resultType都写上

#与$的区别

  • #{} 的作用主要是替换预编译语句(PrepareStatement)中的占位符? ,其可以防止SQL注入问题【推荐使用】

    1
    2
    INSERT INTO user (name) VALUES (#{name});
    INSERT INTO user (name) VALUES (?);
  • ${} 的作用是直接进行字符串替换

    1
    2
    INSERT INTO user (name) VALUES ('${name}');
    INSERT INTO user (name) VALUES ('zhangsan');

MyBatis配置解析

核心配置文件

  • mybatis-config.xml 系统核心配置文件
  • MyBatis 的配置文件包含了会深深影响 MyBatis 行为的设置和属性信息。
  • 能配置的内容如下:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
configuration(配置)
properties(属性)
settings(设置)
typeAliases(类型别名)
typeHandlers(类型处理器)
objectFactory(对象工厂)
plugins(插件)
environments(环境配置)
environment(环境变量)
transactionManager(事务管理器)
dataSource(数据源)
databaseIdProvider(数据库厂商标识)
mappers(映射器)
<!-- 注意元素节点的顺序!顺序不对会报错 -->

environments

1
2
3
4
5
6
7
8
9
10
11
12
13
<environments default="development">
<environment id="development">
<transactionManager type="JDBC|MANAGED">
<property name="..." value="..."/>
</transactionManager>
<dataSource type="UNPOOLED|POOLED|JNDI">
<property name="driver" value="${driver}"/>
<property name="url" value="${url}"/>
<property name="username" value="${username}"/>
<property name="password" value="${password}"/>
</dataSource>
</environment>
</environments>

配置MyBatis的多套运行环境,将SQL映射到多个不同的数据库上,必须指定其中一个为默认运行环境(通过default指定)

子元素节点:environment

  • 具体的一套环境,通过设置id进行区别,id保证唯一
  • 子元素节点:transactionManager - [ 事务管理器 ]
  • 子元素节点:数据源(dataSource)
    • dataSource 元素使用标准的 JDBC 数据源接口来配置 JDBC 连接对象的资源。
    • 数据源是必须配置的。
    • 有三种内建的数据源类型
    • unpooled: 这个数据源的实现只是每次被请求时打开和关闭连接。
    • pooled: 这种数据源的实现利用“池”的概念将 JDBC 连接对象组织起来 , 这是一种使得并发 Web 应用快速响应请求的流行处理方式。
    • jndi:这个数据源的实现是为了能在如 Spring 或应用服务器这类容器中使用,容器可以集中或在外部配置数据源,然后放置一个 JNDI 上下文的引用。
    • 数据源也有很多第三方的实现,比如dbcp,c3p0,druid等等….

mappers

映射器 : 定义映射SQL语句文件。

引入资源方式

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
<!-- 使用相对于类路径的资源引用 -->
<mappers>
<mapper resource="org/mybatis/builder/PostMapper.xml"/>
</mappers>

<!-- 使用完全限定资源定位符(URL) -->
<mappers>
<mapper url="file:///var/mappers/AuthorMapper.xml"/>
</mappers>

<!-- 使用映射器接口实现类的完全限定类名需要配置文件名称和接口名称一致,并且位于同一目录下--><mappers>
<mapper class="org.mybatis.builder.AuthorMapper"/>
</mappers>

<!-- 将包内的映射器接口实现全部注册为映射器但是需要配置文件名称和接口名称一致,并且位于同一目录下-->
<mappers>
<package name="org.mybatis.builder"/>
</mappers>

Mapper文件

1
2
3
<?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.zhao.mapper.UserMapper"></mapper>

namespace中文意思:命名空间,作用如下:

  1. namespace和子元素的id联合保证唯一,区别不同的mapper
  2. 绑定DAO接口
    • namespace的命名必须跟某个接口同名
    • 接口中的方法与映射文件中sql语句id应该一一对应
  3. namespace命名规则 : 包名+类名

typeAliases

类型别名是为 Java 类型设置一个短的名字。它只和 XML 配置有关,存在的意义仅在于用来减少类完全限定名的冗余。

1
2
3
4
<!--配置别名,注意顺序-->
<typeAliases>
<typeAlias type="com.zhao.pojo.User" alias="User"/>
</typeAliases>

当这样配置时,User可以用在任何使用com.zhao.pojo.User的地方。也可以指定一个包名,MyBatis 会在包名下面搜索需要的 Java Bean,比如:

1
2
3
<typeAliases>
<package name="com.zhao.pojo"/>
</typeAliases>

每一个在包 com.zhao.pojo 中的 Java Bean,在没有注解的情况下,会使用 Bean 的首字母小写的非限定类名来作为它的别名。

若有注解,则别名为其注解值:

1
2
3
4
@Alias("user")
public class User {
...
}

settings

设置(settings)相关

  • 懒加载
  • 日志实现
  • 缓存开启关闭

一个配置完整的 settings 元素的示例如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
<settings>  
<setting name="cacheEnabled" value="true"/>
<setting name="lazyLoadingEnabled" value="true"/>
<setting name="multipleResultSetsEnabled" value="true"/>
<setting name="useColumnLabel" value="true"/>
<setting name="useGeneratedKeys" value="false"/>
<setting name="autoMappingBehavior" value="PARTIAL"/>
<setting name="autoMappingUnknownColumnBehavior" value="WARNING"/>
<setting name="defaultExecutorType" value="SIMPLE"/>
<setting name="defaultStatementTimeout" value="25"/>
<setting name="defaultFetchSize" value="100"/>
<setting name="safeRowBoundsEnabled" value="false"/>
<setting name="mapUnderscoreToCamelCase" value="false"/>
<setting name="localCacheScope" value="SESSION"/>
<setting name="jdbcTypeForNull" value="OTHER"/>
<setting name="lazyLoadTriggerMethods" value="equals,clone,hashCode,toString"/>
</settings>

ResultMap

要解决的问题:pojo属性名和数据库字段名不一致。解决方案:

  1. 方案一:为字段名指定别名,别名和java实体类的属性名一致 .

    1
    2
    3
    <select id="selectUserById" resultType="User">    
    select id, name, pwd as password from user where id = #{id}
    </select>

2. 方案二:使用结果集映射->ResultMap 【推荐】

1
2
3
4
5
6
7
8
9
10
11
<resultMap id="UserMap" type="User"> 
<!-- id为主键 -->
<id column="id" property="id"/>
<!-- column是数据库表的列名 , property是对应实体类的属性名 -->
<result column="name" property="name"/>
<result column="pwd" property="password"/>
</resultMap>

<select id="selectUserById" resultMap="UserMap">
select id, name, pwd from user where id = #{id}
</select>

自动映射

  • resultMap 元素是 MyBatis 中最重要最强大的元素。它可以让开发人员从 90% 的 JDBC ResultSets 数据提取代码中解放出来。
  • ResultMap 的设计思想是,对于简单的语句根本不需要配置显式的结果映射,而对于复杂一点的语句只需要描述它们的关系就行了。

默认情况没有显式指定 resultMap。比如:

1
2
3
<select id="selectUserById" resultType="map">
select id, name, pwd from user where id = #{id}
</select>

上述语句只是简单地将所有的列映射到 HashMap 的键上,这由 resultType 属性指定。虽然在大部分情况下都够用,但是 HashMap 不是一个很好的模型。我们的程序更可能会使用 JavaBean 或 POJO(Plain Old Java Objects,普通老式 Java 对象)作为模型。

手动映射

  1. 返回值类型为resultMap
1
2
3
<select id="selectUserById" resultMap="UserMap">
select id, name, pwd from user where id = #{id}
</select>
  1. 编写resultMap,实现手动映射
1
2
3
4
5
6
7
8
9
10
11
<resultMap id="UserMap" type="User">
<!-- id为主键 -->
<id column="id" property="id"/>
<!-- column是数据库表的列名, property是对应实体类的属性名 -->
<result column="name" property="name"/>
<result column="pwd" property="password"/>
<collection property="attrs" ofType="User">
<result column="attr_name" property="attrName"></result>
<result column="attr_value" property="attrValue"></result>
</collection>
</resultMap>

其中,可以在 collection 标签内进行自定义结果集(集合数据),常用于返回结果较为复杂的情况。例如类中嵌套一个集合,此时无法自动解析出返回的集合数据结果,需要使用 collection 自定义集合。

使用注解开发

使用注解开发时不需要再写mapper.xml文件,直接在接口类的方法上添加注解即可。共有四个注解 :

  • @select()
  • @update()
  • @Insert()
  • @delete()
1
2
3
//查询全部用户
@Select("select id,name,pwd password from user")
public List<User> getAllUser();
1
2
3
//根据id查询用户
@Select("select * from user where id = #{id}")
User selectUserById(@Param("id") int id);
1
2
3
//添加一个用户
@Insert("insert into user (id,name,pwd) values (#{id},#{name},#{pwd})")
int addUser(User user);
1
2
3
//修改一个用户
@Update("update user set name=#{name},pwd=#{pwd} where id = #{id}")
int updateUser(User user);
1
2
3
//根据id删除用
@Delete("delete from user where id = #{id}")
int deleteUser(@Param("id")int id);

MyBatis执行流程分析

1
2
3
//查询全部用户
@Select("select id,name,pwd password from user")
public List<User> getAllUser();
1
2
3
4
<!--使用class绑定接口-->
<mappers>
<mapper class="com.zhao.mapper.UserMapper"/>
</mappers>
1
2
3
4
5
6
7
8
9
10
11
12
@Test
public void testGetAllUser() {
SqlSession session = MybatisUtils.getSession();
//本质上利用了jvm的动态代理机制
UserMapper mapper = session.getMapper(UserMapper.class);

● List<User> users = mapper.getAllUser();
for (User user : users){
System.out.println(user);
}
session.close();
}

利用Debug查看本质

img

sqlSession对象内包含:

  • configuration:用于加载mybatis-config.xml文件中的所有配置信息;
  • executor:执行器,用于执行sql语句,含有缓存等信息。

mapper对象是指定Mapper接口的动态代理类,包含:

  • sqlSession:每个mapper都拥有一份sqlSession对象,用于执行sql语句;
  • mapperInterface:通过反射机制获取Mapper接口的全路径名等信息;
  • methodCache:方法缓存,包含接口的每个方法和实现。

首先通过反射机制从session.getMapper(UserMapper.class);中获取到接口信息,然后动态创建出一个代理类对象mapper,其实现了接口的所有方法,使用该代理类执行相应的sql语句。

本质上利用了jvm的动态代理机制

img

Mybatis详细的执行流程

img

多对一处理

多对一的理解:多个学生对应一个老师

按查询嵌套处理

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
<?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.zhao.mapper.StudentMapper">
<!--
需求:获取所有学生及对应老师的信息
思路:
1. 获取所有学生的信息
2. 根据获取的学生信息的老师ID->获取该老师的信息
3. 思考问题,这样学生的结果集中应该包含老师,该如何处理呢,数据库中我们一般使用关联查询?
1. 做一个结果集映射:StudentTeacher
2. StudentTeacher结果集的类型为 Student
3. 学生中老师的属性为teacher,对应数据库中为tid。
多个 [1,...)学生关联一个老师=> 一对一,一对多
4. 查看官网找到:association – 一个复杂类型的关联;使用它来处理关联查询
-->
<select id="getStudents" resultMap="StudentTeacher">
select * from student
</select>

<resultMap id="StudentTeacher" type="Student">
<!--association关联属性 property属性名 javaType属性类型 column在多的一方的表中的列名-->
<association property="teacher" column="tid" javaType="Teacher" select="getTeacher"/>
</resultMap>

<!--
这里传递过来的id,只有一个属性的时候,下面可以写任何值
association中column多参数配置:
column="{key=value,key=value}"
其实就是键值对的形式,key是传给下个sql的取值名称,value是片段一中sql查询的字段名。
-->
<select id="getTeacher" resultType="teacher">
select * from teacher where id = #{id}
</select>
</mapper>

按结果嵌套处理

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
<!--
按查询结果嵌套处理
思路:
1. 直接查询出结果,进行结果集的映射
-->
<select id="getStudents2" resultMap="StudentTeacher2" >
select s.id sid, s.name sname, t.name tname
from student s, teacher t
where s.tid = t.id
</select>

<resultMap id="StudentTeacher2" type="Student">
<id property="id" column="sid"/>
<result property="name" column="sname"/>
<!--关联对象property 关联对象在Student实体类中的属性-->
<association property="teacher" javaType="Teacher">
<result property="name" column="tname"/>
</association>
</resultMap>

小结

  • 按照查询进行嵌套处理就像SQL中的子查询
  • 按照结果进行嵌套处理就像SQL中的联表查询

一对多处理

一对多的理解:一个老师拥有多个学生,即一个老师拥有一群学生(集合)

按结果嵌套处理

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
<mapper namespace="com.zhao.mapper.TeacherMapper">
<!--
思路:
1. 从学生表和老师表中查出学生id,学生姓名,老师姓名
2. 对查询出来的操作做结果集映射
1. 集合的话,使用collection!
JavaType和ofType都是用来指定对象类型的
JavaType是用来指定pojo中属性的类型
ofType指定的是映射到list集合属性中pojo的类型。
-->
<select id="getTeacher" resultMap="TeacherStudent">
select s.id sid, s.name sname , t.name tname, t.id tid
from student s,teacher t
where s.tid = t.id and t.id=#{id}
</select>

<resultMap id="TeacherStudent" type="Teacher">
<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>
</mapper>

按查询嵌套处理

1
2
3
4
5
6
7
8
9
10
11
12
<select id="getTeacher2" resultMap="TeacherStudent2">
select * from teacher where id = #{id}
</select>

<resultMap id="TeacherStudent2" type="Teacher">
<!--column是一对多的外键 , 写的是一的主键的列名-->
<collection property="students" javaType="ArrayList" ofType="Student" column="id" select="getStudentByTeacherId"/>
</resultMap>

<select id="getStudentByTeacherId" resultType="Student">
select * from student where tid = #{id}
</select>

小结

  • 关联-association用于一对一和多对一
  • 集合-collection用于一对多的关系

JavaType和ofType都是用来指定对象类型的

  • JavaType是用来指定pojo中属性的类型
  • ofType指定的是映射到list集合属性中pojo的类型。

动态SQL

官方文档

介绍

什么是动态SQL:动态SQL指的是根据不同的查询条件 , 生成不同的Sql语句.

1
2
3
4
5
6
7
8
9
10
11
官网描述:
MyBatis 的强大特性之一便是它的动态 SQL。如果你有使用 JDBC 或其它类似框架的经验,你就能体会到根据不同条件拼接 SQL 语句的痛苦。例如拼接时要确保不能忘记添加必要的空格,还要注意去掉列表最后一个列名的逗号。利用动态 SQL 这一特性可以彻底摆脱这种痛苦。
虽然在以前使用动态 SQL 并非一件易事,但正是 MyBatis 提供了可以被用在任意 SQL 映射语句中的强大的动态 SQL 语言得以改进这种情形。
动态 SQL 元素和 JSTL 或基于类似 XML 的文本处理器相似。在 MyBatis 之前的版本中,有很多元素需要花时间了解。MyBatis 3 大大精简了元素种类,现在只需学习原来一半的元素便可。MyBatis 采用功能强大的基于 OGNL 的表达式来淘汰其它大部分元素。

-------------------------------
- if
- choose (when, otherwise)
- trim (where, set)
- foreach
-------------------------------

我们之前写的 SQL 语句都比较简单,如果有比较复杂的业务,我们需要写复杂的 SQL 语句,往往需要拼接,而拼接 SQL ,稍微不注意,由于引号,空格等缺失可能都会导致错误。

那么怎么去解决这个问题呢?这就要使用 MyBatis 动态SQL,通过 if, choose, when, otherwise, trim, where, set, foreach等标签,可组合成非常灵活的SQL语句,从而在提高 SQL 语句的准确性的同时,也大大提高了开发人员的效率。

if

需求:根据作者名字和博客名字来查询博客!如果作者名字为空,那么只根据博客名字查询,反之,则根据作者名来查询

1
2
3
4
5
6
7
8
9
10
11
12
13
14
<!--需求1:
根据作者名字和博客名字来查询博客!
如果作者名字为空,那么只根据博客名字查询,反之,则根据作者名来查询
select * from blog where title = #{title} and author = #{author}
-->
<select id="queryBlogIf" parameterType="map" resultType="blog">
select * from blog where
<if test="title != null">
title = #{title}
</if>
<if test="author != null">
and author = #{author}
</if>
</select>

这样写我们可以看到,如果 author 等于 null,那么查询语句为 select * from user where title=#{title},但是如果title为空呢?那么查询语句为 select * from user where and author=#{author},这是错误的 SQL 语句,如何解决呢?请看下面的 where 语句!

where

修改上面的SQL语句:

1
2
3
4
5
6
7
8
9
10
11
<select id="queryBlogIf" 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>

这个“where”标签会知道如果它包含的标签中有返回值的话,它就插入一个‘where’。此外,如果标签返回的内容是以 AND 或 OR 开头的,则它会剔除掉。【使用最频繁】

set

同理,上面的对于查询 SQL 语句包含 where 关键字,如果在进行更新操作的时候,含有 set 关键词,我们怎么处理呢?

1
2
3
4
5
6
7
8
9
10
11
12
13
<!--注意set是用的逗号隔开-->
<update id="updateBlog" parameterType="map">
update blog
<set>
<if test="title != null">
title = #{title},
</if>
<if test="author != null">
author = #{author}
</if>
</set>
where id = #{id};
</update>

choose

有时候,我们不想用到所有的查询条件,只想选择其中的一个,查询条件有一个满足即可,使用 choose 标签可以解决此类问题,类似于 Java 的 switch 语句

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
<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片段

有时候可能某个 sql 语句我们用的特别多,为了增加代码的重用性,简化代码,我们需要将这些代码抽取出来,然后使用时直接调用。

提取SQL片段:

1
2
3
4
5
6
7
8
<sql id="if-title-author">
<if test="title != null">
title = #{title}
</if>
<if test="author != null">
and author = #{author}
</if>
</sql>

引用SQL片段:

1
2
3
4
5
6
7
8
<select id="queryBlogIf" parameterType="map" resultType="blog">
select * from blog
<where>
<!-- 引用 sql 片段,如果refid 指定的不在本文件中,那么需要在前面加上 namespace -->
<include refid="if-title-author"></include>
<!-- 在这里还可以引用其他的 sql 片段 -->
</where>
</select>

注意:

  • 最好基于 单表来定义 sql 片段,提高片段的可重用性
  • 在 SQL 片段中不要包括 where

foreach

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
<select id="queryBlogForeach" parameterType="map" resultType="blog">
select * from blog
<where>
<!--
collection:指定输入对象中的集合属性
item:每次遍历生成的对象
open:开始遍历时的拼接字符串
close:结束时拼接的字符串
separator:遍历对象之间需要拼接的字符串
select * from blog where 1=1 and (id=1 or id=2 or id=3)
-->
<foreach collection="ids" item="id" open="and (" close=")" separator="or">
id=#{id}
</foreach>
</where>
</select>

测试

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
@Test
public void testQueryBlogForeach(){
SqlSession session = MybatisUtils.getSession();
BlogMapper mapper = session.getMapper(BlogMapper.class);

HashMap map = new HashMap();
List<Integer> ids = new ArrayList<Integer>();
ids.add(1);
ids.add(2);
ids.add(3);

map.put("ids",ids);
List<Blog> blogs = mapper.queryBlogForeach(map);

System.out.println(blogs);
session.close();
}

MyBatis 缓存

简介

什么是缓存 [ Cache ]?

  • 存在内存中的临时数据。
  • 将用户经常查询的数据放在缓存(内存)中,用户去查询数据就不用从磁盘上(关系型数据库数据文件)查询,从缓存中查询,从而提高查询效率,解决了高并发系统的性能问题。

为什么使用缓存?:减少和数据库的交互次数,减少系统开销,提高系统效率。什么样的数据能使用缓存?:经常查询并且不经常改变的数据。

Mybatis缓存

MyBatis包含一个非常强大的查询缓存特性,它可以非常方便地定制和配置缓存。缓存可以极大的提升查询效率。

MyBatis系统中默认定义了两级缓存:一级缓存二级缓存

  • 默认情况下,只有一级缓存开启,他是SqlSession级别的缓存,也称为本地缓存
  • 二级缓存需要手动开启和配置,他是基于namespace级别的缓存
  • 为了提高扩展性,MyBatis定义了缓存接口Cache。我们可以通过实现Cache接口来自定义二级缓存
  • 新的会话查询前会先查找二级缓存中是否有对应数据,若没有再去数据库查找

一级缓存

一级缓存也叫本地缓存:

  • 与数据库同一次会话期间(SqlSession)查询到的数据会放在本地缓存中。
  • 以后如果需要获取相同的数据,直接从缓存中拿,没必须再去查询数据库;
1
2
3
4
5
6
7
8
9
10
11
12
13
14
@Test
public void testQueryUserById(){
SqlSession session = MybatisUtils.getSession();
UserMapper mapper = session.getMapper(UserMapper.class);

User user1 = mapper.queryUserById(1);
System.out.println(user1);

User user2 = mapper.queryUserById(1);
System.out.println(user2);

System.out.println(user1==user2);
session.close();
}

user1==user2判断结果为true,即同一个SqlSession中查询到的数据会保存到一级缓存中。每个sqlSession中的缓存相互独立

一级缓存失效的情况:

  • 两次查询之间执行了增删改操作(因为增删改操作可能会对当前数据产生影响,所以一级缓存清空)
  • 手动清除一级缓存session.clearCache();

一级缓存就是一个map

二级缓存

二级缓存也叫全局缓存,一级缓存作用域太低了,所以诞生了二级缓存。二级缓存是基于namespace级别的缓存,一个名称空间,对应一个二级缓存;

工作机制:

  • 一个会话查询一条数据,这个数据就会被放在当前会话的一级缓存中;
  • 如果当前会话关闭了,这个会话对应的一级缓存就没了;但是我们想要的是,会话关闭了,一级缓存中的数据被保存到二级缓存中;
  • 新的会话查询信息,就可以从二级缓存中获取内容;
  • 不同的mapper查出的数据会放在自己对应的缓存(map)中

开启二级缓存步骤:

  1. 开启全局缓存 【mybatis-config.xml】
1
<setting name="cacheEnabled" value="true"/>
  1. 去每个mapper.xml中配置使用二级缓存
1
2
<cache eviction="FIFO" flushInterval="60000" size="512" readOnly="true"/>
<!-- 这个更高级的配置创建了一个 FIFO 缓存,每隔 60 秒刷新,最多可以存储结果对象或列表的 512 个引用,而且返回的对象被认为是只读的,因此对它们进行修改可能会在不同线程中的调用者产生冲突。 -->
  1. 代码测试
  • 所有的实体类先实现序列化接口
  • 测试
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
@Test
public void testQueryUserById(){
SqlSession session = MybatisUtils.getSession();
SqlSession session2 = MybatisUtils.getSession();

UserMapper mapper = session.getMapper(UserMapper.class);
UserMapper mapper2 = session2.getMapper(UserMapper.class);
User user = mapper.queryUserById(1);

System.out.println(user);
session.close();

User user2 = mapper2.queryUserById(1);

System.out.println(user2);
System.out.println(user==user2);
session2.close();
}

结论

  • 只要开启了二级缓存,我们在同一个Mapper中的查询,可以在二级缓存中拿到数据
  • 查出的数据都会被默认先放在一级缓存中
  • 只有会话提交或者关闭以后,一级缓存中的数据才会转到二级缓存中

缓存原理

新会话创建后本身没有一级缓存,其在查询前会先在二级缓存中查找是否有对应的数据,若没有再去数据库查找

img

EhCache

第三方缓存实现—EhCache:Ehcache是一种广泛使用的java分布式缓存,用于通用缓存。官方文档

要在应用程序中使用Ehcache,需要引入依赖的jar包

1
2
3
4
5
6
<!-- https://mvnrepository.com/artifact/org.mybatis.caches/mybatis-ehcache -->
<dependency>
<groupId>org.mybatis.caches</groupId>
<artifactId>mybatis-ehcache</artifactId>
<version>1.1.0</version>
</dependency>

在mapper.xml中使用对应的缓存即可

1
2
3
<mapper namespace = “org.acme.FooMapper” > 
<cache type = “org.mybatis.caches.ehcache.EhcacheCache” />
</mapper>

编写ehcache.xml文件,如果在加载时未找到/ehcache.xml资源或出现问题,则将使用默认配置。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
<?xml version="1.0" encoding="UTF-8"?>
<ehcache xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:noNamespaceSchemaLocation="http://ehcache.org/ehcache.xsd"
updateCheck="false">
<!--
diskStore:为缓存路径,ehcache分为内存和磁盘两级,此属性定义磁盘的缓存位置。参数解释如下:
user.home – 用户主目录
user.dir – 用户当前工作目录
java.io.tmpdir – 默认临时文件路径
-->
<diskStore path="./tmpdir/Tmp_EhCache"/>
<defaultCache eternal="false"
maxElementsInMemory="10000"
overflowToDisk="false"
diskPersistent="false"
timeToIdleSeconds="1800"
timeToLiveSeconds="259200"
memoryStoreEvictionPolicy="LRU"/>
<cache name="cloud_user"
eternal="false"
maxElementsInMemory="5000"
overflowToDisk="false"
diskPersistent="false"
timeToIdleSeconds="1800"
timeToLiveSeconds="1800"
memoryStoreEvictionPolicy="LRU"/>
<!--
defaultCache:默认缓存策略,当ehcache找不到定义的缓存时,则使用这个缓存策略。只能定义一个。
-->
<!--
name:缓存名称。
maxElementsInMemory:缓存最大数目
maxElementsOnDisk:硬盘最大缓存个数。
eternal:对象是否永久有效,一但设置了,timeout将不起作用。
overflowToDisk:是否保存到磁盘,当系统当机时
timeToIdleSeconds:设置对象在失效前的允许闲置时间(单位:秒)。仅当eternal=false对象不是永久有效时使用,可选属性,默认值是0,也就是可闲置时间无穷大。
timeToLiveSeconds:设置对象在失效前允许存活时间(单位:秒)。最大时间介于创建时间和失效时间之间。仅当eternal=false对象不是永久有效时使用,默认是0.,也就是对象存活时间无穷大。
diskPersistent:是否缓存虚拟机重启期数据 Whether the disk store persists between restarts of the Virtual Machine. The default value is false.
diskSpoolBufferSizeMB:这个参数设置DiskStore(磁盘缓存)的缓存区大小。默认是30MB。每个Cache都应该有自己的一个缓冲区。
diskExpiryThreadIntervalSeconds:磁盘失效线程运行时间间隔,默认是120秒。
memoryStoreEvictionPolicy:当达到maxElementsInMemory限制时,Ehcache将会根据指定的策略去清理内存。默认策略是LRU(最近最少使用)。你可以设置为FIFO(先进先出)或是LFU(较少使用)。
clearOnFlush:内存数量最大时是否清除。
memoryStoreEvictionPolicy:可选策略有:LRU(最近最少使用,默认策略)、FIFO(先进先出)、LFU(最少访问次数)。
FIFO,first in first out,这个是大家最熟的,先进先出。
LFU, Less Frequently Used,就是上面例子中使用的策略,直白一点就是讲一直以来最少被使用的。如上面所讲,缓存的元素有一个hit属性,hit值最小的将会被清出缓存。
LRU,Least Recently Used,最近最少使用的,缓存的元素有一个时间戳,当缓存容量满了,而又需要腾出地方来缓存新的元素的时候,那么现有缓存元素中时间戳离当前时间最远的元素将被清出缓存。
-->
</ehcache>

面试题

https://www.kuangstudy.com/bbs/1478198733996175361