SSM框架之Mybatis学习笔记

Mybatis

1. 概述

环境:

  • JDK 1.8
  • MySQL 5.7
  • maven 3.6.1
  • IDEA

需要知识:

  • JDBC、MySQL、java基础、Maven、Junit

框架:有很多配置文件。学习方式:看官网文档。
官网文档:https://mybatis.org/mybatis-3/index.html

什么是Mybatis

  • MyBatis 是一款优秀的持久层框架(持久层:完成持久化工作的代码块)
  • 它支持自定义SQL、存储过程以及高级映射
  • MyBatis 免除了几乎所有的JDBC代码以及设置参数和获取结果集的工作。
  • MyBatis 可以通过简单的 XML 或注解来配置和映射原始类型、接口和 Java POJO(Plain Old Java Objects,普通老式 Java 对象)为数据库中的记录。
  • MyBatis本是apache的一个开源项目iBatis,2010年这个项目由apache software foundation 迁移到了google code,并且改名为MyBatis。
  • 2013年11月迁移到Github。

获取Mybatis:https://github.com/mybatis/mybatis-3/releases

Maven仓库:

<!-- https://mvnrepository.com/artifact/org.mybatis/mybatis -->
<dependency>
    <groupId>org.mybatis</groupId>
    <artifactId>mybatis</artifactId>
    <version>3.5.2</version>
</dependency>

为什么需要Mybatis

  • 帮助程序员将数据存入到数据库中
  • 方便
  • 传统的JDBC代码太复杂了。
  • 不用Mybatis也可以。更容易上手。技术没有高低之分
  • 优点:
    • 简单易学
    • 灵活
    • sql和代码的分离,提高了可维护性。
    • 提供映射标签,支持对象与数据库的orm字段关系映射。
    • 提供对象关系映射标签,支持对象关系组建维护
    • 提供xml标签,支持编写动态sql。

最重要的一点:使用的人多!


2. 入门案例:查询

Mybatis核心接口:SqlSessionFactoryBuilder、SqlSessionFactory、SqlSession

1. 环境搭建
创建一个数据库,在数据库中创建一张表,添加一些字段。

CREATE DATABASE `mybatis`;
USE `mybatis`;
CREATE table `user` (
	`id` INT(20) not null primary key,
	`name` varchar(30) DEFAULT null,
	`pwd` varchar(30) DEFAULT NULL
)ENGINE=INNODB DEFAULT CHARSET=utf8;
insert into `user`(`id`,`name`,`pwd`) values (1,'张三','123456'),(2,'李四','456789'),(3,'王五','654321');

2. 新建项目
创建一个普通的maven项目,删除src目录,然后在项目中添加子模块。
导入需要的依赖:

<dependencies>
<!-- mysql驱动-->
<dependency>
    <groupId>mysql</groupId>
    <artifactId>mysql-connector-java</artifactId>
    <version>5.1.32</version>
</dependency>
<!--mybatis-->
<dependency>
    <groupId>org.mybatis</groupId>
    <artifactId>mybatis</artifactId>
    <version>3.4.5</version>
</dependency>
<!--junit-->
<dependency>
    <groupId>junit</groupId>
    <artifactId>junit</artifactId>
    <version>4.12</version>
    <scope>test</scope>
</dependency>
</dependencies>

3. 在resource中编写mybatis的核心配置文件:mybatis-config.xml

<?xml version="1.0" encoding="UTF8" ?>
<!DOCTYPE configuration
        PUBLIC "-//mybatis.org//DTD config 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
    <environments default="development">
        <environment id="development">
            <transactionManager type="JDBC"/>
            <dataSource type="POOLED">
                <property name="driver" value="com.mysql.jdbc.Driver"/>
                <property name="url" value="jdbc:mysql://localhost:3306/mybatis?useSSL=true&amp;useUnicode=true&amp;characterEncoding=UTF-8"/>
                <property name="username" value="账户"/>
                <property name="password" value="密码"/>
            </dataSource>
        </environment>
    </environments>
    <!-- 每一个Mapper.XML都需要在Mybatis核心配置文件中注册! -->
    <mappers>
        <mapper resource="com/kuang/dao/UserDao.xml"/>
    </mappers>
</configuration>

4. 编写mybatis工具类

//sqlSessionFactory --> sqlSession
public class MybatisUtils {

    private static SqlSessionFactory sqlSessionFactory;

    static {
        InputStream inputStream = null;
        try {
            //使用mybatis第一步获取sqlSessionFactory对象
            String resource = "mybatis-config.xml";
            inputStream = Resources.getResourceAsStream(resource);
            sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

    //既然有了 SqlSessionFactory,顾名思义,我们可以从中获得 SqlSession 的实例。
    // SqlSession 提供了在数据库执行 SQL 命令所需的所有方法。你可以通过 SqlSession 实例来直接执行已映射的 SQL 语句。
    public static SqlSession getSqlSession() {
        return sqlSessionFactory.openSession();
    }
    
}

5. 编写pojo实体类

public class User {
    private int id;
    private String name;
    private String pwd;
    .... //构造方法、getter和setter方法、toString方法
}

6. 创建Dao接口,以及实现
在javaweb中是要创建一个类去继承Dao接口,在mybatis中是写mapper配置文件。

public interface UserDao {
    List<User> getUserList();
}

id属性,要和namespace接口中的方法名一致。

<?xml version="1.0" encoding="UTF8" ?>
<!DOCTYPE mapper
        PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<!--namespace=绑定一个对应的Dao/Mapper接口-->
<mapper namespace="com.kuang.dao.UserDao">
    <!--sql查询语句-->
    <select id="getUserList" resultType="com.kuang.pojo.User">
        select * from mybatis.user
    </select>
</mapper>

7. 测试

@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.kuang.dao.UserDao.getUserList");

    for(User user : userList) {
        System.out.println(user);
    }

    //关闭SqlSession
    sqlSession.close();
}

这里可能会出现一个问题:我们的mapper.xml写在java文件中,会导致资源导出失败
在pom.xml中加上这段配置:

<!--在build中配置resources,来防止我们资源导出失败的问题-->
<build>
    <resources>
        <resource>
            <directory>src/main/resources</directory>
            <includes>
                <include>**/*.properties</include>
                <include>**/*.xml</include>
            </includes>
            <filtering>true</filtering>
        </resource>
        <resource>
            <directory>src/main/java</directory>
            <includes>
                <include>**/*.properties</include>
                <include>**/*.xml</include>
            </includes>
            <filtering>true</filtering>
        </resource>
    </resources>
</build>

注意:框架的学习,环境是特别重要的,代码相同环境不同,也可能会出现问题。

3. CRUD

根据入门案例,以后只需要修改UserDao和UserMapper.xml,然后测试。

两个参数说明:
resultType:返回值
parameterType:参数类型

  • 根据id查询
    public interface UserDao {
        User getUserById(int id);
    }
    
    <mapper namespace="com.kuang.dao.UserDao">
        <select id="getUserById" resultType="com.kuang.pojo.User" parameterType="int">
            select * from mybatis.user where id = #{id}
        </select>
    </mapper>
    
    @Test
    public void getUserById() {
        SqlSession sqlSession = MybatisUtils.getSqlSession();
    
        UserDao mapper = sqlSession.getMapper(UserDao.class);
        User user = mapper.getUserById(1);
        System.out.println(user);
    
        sqlSession.close();
    }
    
  • 增加用户

    public interface UserDao {
        int addUser(User user);
    }
    

    pojo实体类中的字段要和 #{ } 中的字段对应,也就是parameterType中的字段

    <mapper namespace="com.kuang.dao.UserDao">
        <insert id="addUser" parameterType="com.kuang.pojo.User">
            insert into mybatis.user (id,name,pwd) values (#{id},#{name},#{pwd})
        </insert>
    </mapper>
    

    注意:增删改操作需要提交事务!

    @Test
    public void addUser() {
        SqlSession sqlSession = MybatisUtils.getSqlSession();
        
        UserDao mapper = sqlSession.getMapper(UserDao.class);
        User user = new User(4,"阿修罗", "2342324");
        mapper.addUser(user);
        sqlSession.commit(); //提交事务
        
        sqlSession.close();
    }
    
  • 修改用户

    public interface UserDao {
        int updateUser(User user);
    }
    
    <mapper namespace="com.kuang.dao.UserDao">
        <update id="updateUser" parameterType="com.kuang.pojo.User">
            update mybatis.user set name=#{name},pwd=#{pwd} where id = #{id};
        </update>
    </mapper>
    
    @Test
    public void updateUser() {
        SqlSession sqlSession = MybatisUtils.getSqlSession();
        UserDao mapper = sqlSession.getMapper(UserDao.class);
        mapper.updateUser(new User(4,"斑", "53453"));
        sqlSession.commit();
        sqlSession.close();
    }
    
  • 根据id删除用户

    public interface UserDao {
        int deleteUser(int id);
    }
    
    <mapper namespace="com.kuang.dao.UserDao">
    	<delete id="deleteUser" parameterType="int">
        	delete from mybatis.user where id = #{id};
    	</delete>
    </mapper>
    
    @Test
    public void deleteUser() {
        SqlSession sqlSession = MybatisUtils.getSqlSession();
        UserDao mapper = sqlSession.getMapper(UserDao.class);
        mapper.deleteUser(4);
        sqlSession.commit();
        sqlSession.close();
    }
    

    注意点:
    resultType、parameterType,返回值类型和参数类型;
    增删改需要提交事务;
    SQL标签中的id属性,对应namespace接口中的方法名;
    #{ }中的字段,对应pojo实体类的字段。所以,尽量保持数据库字段名和实体类中的变量名相同。

  • Map
    假设我们的实体类,或者数据库中的表,字段或者参数过多,可以考虑使用Map

    public interface UserDao {
    	int addUser2(Map<String,Object> map);
    }
    

    这种方式,#{ } 不需要和namespace接口的字段名对应,而且字段可以为null的可以不插入。是一种万能的方式。

    <mapper namespace="com.kuang.dao.UserDao">
        <insert id="addUser2" parameterType="map">
            insert into mybatis.user (id,name,pwd) values(#{userId},#{userName},#{userPassword});
        </insert>
    </mapper>
    
    @Test
    public void addUser2() {
        SqlSession sqlSession = MybatisUtils.getSqlSession();
        
        UserDao mapper = sqlSession.getMapper(UserDao.class);
        Map<String,Object> map = new HashMap<>();
        map.put("userId",5);
        map.put("userName","柱间");
        map.put("userPassword", "5345654");
        mapper.addUser2(map);
        sqlSession.commit();
        
        sqlSession.close();
    }
    

    Map传递参数,直接在SQL中取出key即可【parameterType=“map”】

    对象传递参数,直接在SQL中取对象的属性即可【parameterType=“Object”】

    只有一个基本类型参数的情况下,可以直接在SQL中取到(parameterType=" " 这个属性可以省略)。

    多个参数用Map,或者注解。

  • 模糊查询的写法
    1. Java代码执行的时候,传递通配符 % %

    public interface UserDao {
    	List<User> userList(String name);
    }
    
    <select id="userList" resultType="com.kuang.pojo.User">
        select * from mybatis.user where name like #{values};
    </select>
    
    @Test
    public void userList() {
        SqlSession sqlSession = MybatisUtils.getSqlSession();
        UserDao mapper = sqlSession.getMapper(UserDao.class);
        
        List<User> userList = mapper.userList("%李%");
        
        for (User user :userList) {
            System.out.println(user);
        }
        sqlSession.close();
    }
    

    2. 在SQL拼接使用通配符

    <select id="userList" resultType="com.kuang.pojo.User">
        select * from mybatis.user where name like %#{values}%;
    </select>
    
    List<User> userList = mapper.userList("李");
    

4. 配置解析

Mybatis的配置文件包含了会深深影响Mybatis行为的设置和属性信息。

configuration(配置)
properties(属性)
settings(设置)
typeAliases(类型别名)
typeHandlers(类型处理器)
objectFactory(对象工厂)
plugins(插件)
environments(环境配置)
environment(环境变量)
transactionManager(事务管理器)
dataSource(数据源)
databaseIdProvider(数据库厂商标识)
mappers(映射器)

  • 环境配置(environments): MyBatis可以配置成适应多种环境
    不过要记住:尽管可以配置多个环境,但每个 SqlSessionFactory 实例只能选择一种环境。
    通过id选择哪一个环境

    <environments default="development">
        <environment id="development">
            <transactionManager type="JDBC"/>
            <dataSource type="POOLED">
                <property name="driver" value="com.mysql.jdbc.Driver"/>
                <property name="url" value="jdbc:mysql://localhost:3306/mybatis?useSSL=true&amp;useUnicode=true&amp;characterEncoding=UTF-8"/>
                <property name="username" value="root"/>
                <property name="password" value="qwer`123"/>
            </dataSource>
        </environment>
        
        <environment id="test">
        	...
        </environment>
    </environments>
    
  • transactionManager:事务管理器
    在Mybatis中有两种类型的事务管理器:JDBC | MANAGED。

  • dataSource:数据源
    UNPOOLED | POOLED | JNDI

  • properties:属性
    我们可以通过properties属性来实现引用配置文件
    这些属性可以在外部进行配置,并可以进行动态替换。你既可以在典型的 Java 属性文件中配置这些属性,也可以在 properties 元素的子元素中设置。【db.properties】
    编写一个配置文件db.properties

    driver=com.mysql.jdbc.Driver
    url=jdbc:mysql://localhost:3306/mybatis?useSSL=true&useUnicode=true&characterEncoding=UTF-8
    username=root
    password=qwer`123
    

    然后,在mybatis-config.xml中引入外部配置文件
    注意:xml中标签是规定了顺序的,也就是标签不能写在任意位置。

    <!-- 引入外部配置文件 -->
    <properties resource="db.properties"/>
    
    <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>
    

    或者,不在外部配置文件配置,给properties标签添加属性。

    <properties resource="db.properties">
    	<property name="username" value="root">
    	<property name="pwd" value="qwer`123">
    </properties>
    
    <property name="username" value="${username}"/>
    <property name="pwd" value="${password}"/>
    

    如果在外部配置文件配了,属性也添加了,那么优先走外部配置文件。

  • typeAliases:类型别名
    类型别名可为 Java 类型设置一个缩写名字,意在降低冗余的全限定类名书写。
    1. 第一种方式:自定义别名

    <typeAliases>
    	<typeAlias type="com.kuang.pojo.User" alias="user"/>
    </typeAliases>
    

    2. 第二种方式:扫描实体类的包,别名为这个类的小写

    <typeAliases>
    	<package name="com.kuang.pojo"/>
    </typeAliases>
    

    3. 第三种方式:在实体类上加注解

    @Alias("user")
    public class user{}
    
    <select id="getUserList" resultType="user">
        select * from mybatis.user
    </select>
    
  • settings:设置
    这是Mybatis中极为重要的调整设置,它们会改变Mybatis的运行时行为。
    这里列出比较重要的三个:

    cacheEnabled: 全局性地开启或关闭所有映射器配置文件中已配置的任何缓存。

    lazyLoadingEnabled: 延迟加载的全局开关。当开启时,所有关联对象都会延迟加载。 特定关联关系中可通过设置fetchType 属性来覆盖该项的开关状态。

    logImpl:指定 MyBatis 所用日志的具体实现,未指定时将自动查找。

  • mappers:映射器
    MapperRegistry:注册绑定我们的Mapper文件
    方式一:mapper标签中的resource属性

    <mappers>
    	<mapper resource="com/kuang/dao/UserMapper.xml"/>
    </mappers>
    

    方式二:mapper标签的class属性,文件绑定注册

    <mappers>
    	<mapper class="com.kuang.dao.UserMapper"/>
    </mappers>
    

    方式三:使用扫描包进行注入绑定

    <mappers>
    	<package name="com.kuang.dao"/>
    </mappers>
    

    使用方式二和方式三需要注意
    接口和他的Mapper配置文件必须同名
    接口和他的Mapper配置文件必须在同一个包下

  • 声明周期和作用域
    作用域和生命周期类别是至关重要的,因为错误的使用会导致非常严重的并发问题
    在这里插入图片描述
    SqlSessionFactoryBuilder:
    一旦创建了SqlSessionFactory,就不再需要它了。是一个局部变量。

    SqlSessionFactory:
    可以想象为:数据库连接池
    SqlSessionFactory一旦被创建就应该在应用的运行期间一直存在,没有任何理由丢弃它或重新创建另一个实例。
    因此SqlSessionFactory的最佳作用域是应用作用域。
    最简单的就是使用单例模式或者静态单例模式。

    SqlSession:
    连接到连接池的一个请求。
    Sqlsession的实例不是线程安全的,因此是不能被共享的,所以它的最佳的作用域是请求或方法作用域。
    用完之后需要赶紧关闭,否则资源被占用。
    在这里插入图片描述
    SqlSessionFactory可以创建多个SqlSession,SqlSession可以连接多个Mapper。
    这里面的每一个Mapper,就代表一个具体的业务!

5. 解决属性名和字段名不一致的问题。

问题描述:
数据库中的字段是这样的
在这里插入图片描述
而实体类中是这样的
在这里插入图片描述
根据id查询用户,查询结果:
在这里插入图片描述
数据库中的字段名和实体类中的变量名不一样,所以没有查询到结果。

解决方式一:起别名

<select id="getUserById" parameterType="int" resultType="user">
    select id,name,pwd as password from mybatis.user where id = #{id}
</select>

解决方式二:ResultMap结果集映射

<!--column数据库中的字段,property实体类中的属性-->
<resultMap id="UserMap" type="com.kuang.pojo.User">
    <result column="id" property="id"/>
    <result column="name" property="name"/>
    <result column="pwd" property="password"/>
</resultMap>
<!--注意这里的resultMap要和上面的id对应-->
<select id="getUserById" resultMap="UserMap" parameterType="int">
    select id,name,pwd from mybatis.user where id = #{id}
</select>
  • resultMap 元素是 MyBatis 中最重要最强大的元素。
  • ResultMap 的设计思想是,对简单的语句做到零配置,对于复杂一点的语句,只需要描述语句之间的关系就行了。
  • 你完全可以不用显式地配置它们
  • 如果这个世界总是这么简单就好了。

6. 日志工厂

如果一个数据库操作,出现了异常,我们需要排错。日志就是最好的助手!
logImpl: 指定 MyBatis 所用日志的具体实现,未指定时将自动查找。

SLF4J
LOG4J 【掌握】
LOG4J2
JDK_LOGGING
COMMONS_LOGGING
STDOUT_LOGGING【掌握】
NO_LOGGING

在Mybatis中具体使用哪一个日志实现,在设置中设定!

  • STDOUT_LOGGING标准日志输出。默认设置就可以用。

    <settings>
        <setting name="logImpl" value="STDOUT_LOGGING"/>    
    </settings>
    

    注意:配置的时候,name和value一定不能写错,多一个空格也不行

  • log4j
    Log4j是Apache的一个开源项目,通过使用Log4j,我们可以控制日志信息输送的目的地是控制台、文件、GUI组件.
    我们也可以控制每一条日志的输出格式。
    通过定义每一条日志信息的级别,我们能够更加细致地控制日志的生成过程。
    可以通过一个配置文件来灵活地进行配置,而不需要修改应用的代码。

    使用:
    1. 先导入log4J的包

    <!--百度搜索 log4j maven-->
    <dependencies>
        <dependency>
            <groupId>log4j</groupId>
            <artifactId>log4j</artifactId>
            <version>1.2.17</version>
        </dependency>
    </dependencies>
    

    2. log4j.properties

    ### 将等级为DEBUG的日志信息输出到console和file这两个目的地,console和file的定义在下面的代码
    log4j.rootLogger=DEBUG,CONSOLE
    
    ### 输出信息到控制抬 ###
    log4j.logger.demo.mybatis.mydemo2.model=TRACE
    log4j.appender.CONSOLE=org.apache.log4j.ConsoleAppender
    log4j.appender.CONSOLE.layout=org.apache.log4j.PatternLayout
    log4j.appender.console.layout.ConversionPattern=%5p [%t] - %m%n
    
    ### 文件输出的相关设置
    log4j.appender.file = org.apache.log4j.RollingFileAppender
    log4j.appender.file.File = ./log/kuang.log
    log4j.appender.file.MaxFileSize = 10mb
    log4j.appender.file.Threshold = DEBUG 
    log4j.appender.file.layout = org.apache.log4j.PatternLayout
    log4j.appender.file.layout.ConversionPattern = [%p][%d{yy-MM-dd}][%c]%m%n
    
    ### 日志输出级别
    log4j.logger.org.mybatis=DEBUG
    log4j.logger.java.sql=DEBUG
    log4j.logger.java.sql.Statement = DEBUG
    log4j.logger.java.sql.ResultSet = DEBUG 
    log4j.logger.java.sql.PreparedStatement=DEBUG
    

    3. 配置log4j为日志的实现

    <settings>
        <setting name="logImpl" value="LOG4J"/>
    </settings>
    

    4. 简单使用

    import org.apache.log4j.Logger;
    static Logger logger = Logger.getLogger(MybatisTest.class);
    @Test
    public void test2() {
    	//三种日志级别
        logger.info("info:进入了test2");
        logger.debug("debug:进入了test2");
        logger.error("error:进入了test2");
    }
    

    在这里插入图片描述
    会生成一个文件,再次运行会在后面追加信息。

7. 分页

使用limit分页

1. 接口

List<User> getUserLimit(Map<String, Integer> map);

2. mapper.xml实现

<select id="getUserLimit" resultMap="UserMap" parameterType="map">
    select * from mybatis.user limit #{startIndex},#{page}
</select>

3. 测试

@Test
public void test3() {
    SqlSession sqlSession = MybatisUtils.getSqlSession();
    UserMapper mapper = sqlSession.getMapper(UserMapper.class);
    Map<String,Integer> map = new HashMap<>();
    map.put("startIndex",0);
    map.put("page",2);
    List<User> userList = mapper.getUserLimit(map);
    for (User user : userList) {
        System.out.println(user);
    }
    sqlSession.close();
}

RowBounds分页

这种方式实现分页,要依赖SqlSession中的selectList(执行sql的第二种方式)。
1. 接口

public interface UserMapper {
    List<User> getUserRowBounds();
}

2. mapper.xml实现

<mapper namespace="com.kuang.dao.UserMapper">
    <select id="getUserRowBounds" resultMap="UserMap">
        select * from mybatis.user
    </select>
</mapper>

3. 测试

@Test
public void test4() {
    SqlSession sqlSession = MybatisUtils.getSqlSession();
    
    RowBounds rowBounds = new RowBounds(0,2);
    List<User> userList = sqlSession.selectList("com.kuang.dao.UserMapper.getUserRowBounds",null,rowBounds);
    for(User user : userList) {
        System.out.println(user);
    }
    
    sqlSession.close();
}

分页插件

Mybatis分页插件PageHelper

8. 使用注解开发

1. 注解在接口上实现

@Select("select * from user")
List<User> getUsers();

2. 需要在核心配置文件中绑定接口

<!--绑定接口-->
<mappers>
    <mapper class="com.kuang.dao.UserMapper"/>
</mappers>

3. 测试

@Test
public void test() {
    SqlSession sqlSession = MybatisUtils.getSqlSession();
    UserMapper mapper = sqlSession.getMapper(UserMapper.class);
    List<User> userList = mapper.getUsers();
    for (User user : userList) {
        System.out.println(user);
    }
    sqlSession.close();
}

本质:反射机制实现
底层:动态代理

注解的CRUD

之前说过增删改需要提交事务,不然操作不成功。
其实,可以在在Mybatis工具类中设置一个参数,表示默认提交事务。

public static SqlSession getSqlSession() {
    return sqlSessionFactory.openSession(true);
}
  • 根据id查询
    如果方法中有多个参数,所有参数前必须加上@Param。
    不管是用注解方式,还是配置文件的实现方式,#{ } 中的参数,对应@Param中的参数。
    public interface UserMapper {
        @Select("select * from user where id = #{uid}")
        User getUserById(@Param("uid") int id);
    }
    
  • @Insert("insert into user (id,name,pwd) values (#{id},#{name},#{password})")
    int addUser(User user);
    
    mapper.addUser(new User(6, "斑", "348395"));
    
  • @Delete("delete from user where id = #{uid}")
    int deleteUser(@Param("uid") int id);
    
    mapper.deleteUser(6);
    
  • @Update("update user set name=#{name}, pwd=#{password} where id = #{id}")
    int updateUser(User user);
    
    mapper.updateUser(new User(5,"斑","1234543"));
    

关于@Param()注解

基本类型的参数或者String类型,需要加上;
引用类型不需要加;
如果只有一个基本类型的话,可以忽略,但是建议大家都加上;
我们在SQL中引用的就是我们这里的@Param()中设定的属性名。

9. 多对一和一对多处理

多个学生,对应一个老师
对于学生这边而言,关联,多个学生,关联一个老师【多对一】
对于老师而言,集合,一个老师,有多个学生【一对多】

环境搭建

数据库表的创建

CREATE TABLE `teacher` (
  `id` INT(10) NOT NULL,
  `name` VARCHAR(30) DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=INNODB DEFAULT CHARSET=utf8

INSERT INTO teacher(`id`, `name`) VALUES (1, '秦老师');

CREATE TABLE `student` (
  `id` INT(10) NOT NULL,
  `name` VARCHAR(30) DEFAULT NULL,
  `tid` INT(10) DEFAULT NULL,
  PRIMARY KEY (`id`),
  KEY `fktid` (`tid`),
  CONSTRAINT `fktid` FOREIGN KEY (`tid`) REFERENCES `teacher` (`id`)
) ENGINE=INNODB DEFAULT CHARSET=utf8
INSERT INTO `student` (`id`, `name`, `tid`) VALUES (1, '小明', 1); 
INSERT INTO `student` (`id`, `name`, `tid`) VALUES (2, '小红', 1); 
INSERT INTO `student` (`id`, `name`, `tid`) VALUES (3, '小张', 1); 
INSERT INTO `student` (`id`, `name`, `tid`) VALUES (4, '小李', 1); 
INSERT INTO `student` (`id`, `name`, `tid`) VALUES (5, '小王', 1);

在这里插入图片描述

多对一

  1. 创建实体类
    public class Student {
        private int id;
        private String name;
        //每个学生需要关联一个老师
        private Teacher teacher;
        
    public class Teacher {
        private int id;
        private String name;
    
  2. 创建mapper接口
    public interface StudentMapper {
        public List<Student> getStudent();
        public List<Student> getStudent2();
    }
    
  3. 创建mapper.xml
  4. 在mybatis-config.xml核心配置文件中,绑定注册mapper接口
    <mappers>
        <mapper class="com.kuang.dao.TeacherMapper"/>
        <mapper class="com.kuang.dao.StudentMapper"/>
    </mappers>
    
  5. 测试
  • 第一种实现方式:按照查询嵌套处理
    相当于mysql的子查询

    思路:
    查询所有的学生信息
    根据查询出来的学生的tid,寻找对应的老师

    <mapper namespace="com.kuang.dao.StudentMapper">
        <select id="getStudent" resultMap="StudentTeacher">
            select * from student
        </select>
    
        <resultMap id="StudentTeacher" type="com.kuang.pojo.Student">
            <result property="id" column="id"/>
            <result property="name" column="name"/>
            <association property="teacher" column="tid" javaType="com.kuang.pojo.Teacher" select="getTeacher"/>
        </resultMap>
    
        <select id="getTeacher" resultType="com.kuang.pojo.Teacher">
            select * from teacher where id=#{id}
        </select>
    </mapper>
    
  • 第二种方式:按照结果嵌套处理
    相当于mysql的联表查询

    <mapper namespace="com.kuang.dao.StudentMapper">
        <select id="getStudent2" resultMap="StudentTeacher2">
            select
                 s.id sid, s.name sname, t.name tname, t.id tid
            from
                 student s
            join
                teacher t
            on
                s.tid = t.id;
        </select>
        
        <resultMap id="StudentTeacher2" type="Student">
            <result property="id" column="sid"/>
            <result property="name" column="sname"/>
            <association property="teacher" javaType="Teacher">
                <result property="id" column="tid"/>
                <result property="name" column="tname"/>
            </association>
        </resultMap>
    </mapper>
    

一对多

一个老师拥有多个学生
对于老师而言,就是一对多的关系

  1. 创建实体类
    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;
    
  2. 创建mapper接口
    public interface TeacherMapper {
    	//获取指定老师下,所有学生及老师的信息
    	List<Teacher> getTeacher(@Param("tid") int id);
    	List<Teacher> getTeacher2(@Param("tid") int id);
    }
    
  3. 创建mapper.xml
  4. 在mybatis-config.xml核心配置文件中,绑定注册mapper接口
    <mappers>
        <mapper class="com.kuang.dao.TeacherMapper"/>
        <mapper class="com.kuang.dao.StudentMapper"/>
    </mappers>
    
  5. 测试
  • 第一种实现方式:按照查询嵌套处理
    <select id="getTeacher2" resultMap="TeacherStudent2">
        select * from mybatis.teacher where id = #{id}
    </select>
    
    <resultMap id="TeacherStudent2" type="Teacher">
        <collection property="students" javaType="ArrayList" ofType="Student" select="getStudentByTeacherId" column="id"/>
    </resultMap>
    
    <select id="getStudentByTeacherId" resultType="Student">
        select * from mybatis.student where tid = #{tid}
    </select>
    
  • 第二种实现方式:按照结果嵌套查询处理
    <mapper namespace="com.kuang.dao.TeacherMapper">
    
        <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 = #{tid}
        </select>
        <resultMap id="TeacherStudent" type="com.kuang.pojo.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>
    
    </mapper>
    

小结:

  • 关联 - association 【多对一】
  • 集合 -collection 【一对多】
  • javaType & ofType
    javaType 用来指定实体类中属性的类型
    ofType 用来指定映射到List或者集合中的pojo类型,泛型中的约束类型!

10. 动态SQL

什么是动态SQL:动态SQL就是指根据不同的条件生成不同的SQL语句。

例如:拼接SQL要确保不能忘记添加必要的空格,还要注意去掉列表最后一个列名的逗号。利用动态SQL这一特性可以彻底摆脱这种痛苦。

环境搭建

CREATE TABLE `blog`(
`id` VARCHAR(50) NOT NULL COMMENT '博客id',
`title` VARCHAR(100) NOT NULL COMMENT '博客标题',
`author` VARCHAR(30) NOT NULL COMMENT '博客作者',
`create_time` DATETIME NOT NULL COMMENT '创建时间',
`views` INT(30) NOT NULL COMMENT '浏览量'
)ENGINE=INNODB DEFAULT CHARSET=utf8
  1. 编写mybatis-config.xml配置文件。
    绑定的mapper要修改过来。

  2. 编写实体类

    public class Blog {
        private String id;
        private String title;
        private String author;
        private Date create_time;
        private int views;
    
  3. 编写实体类对应Mapper接口和Mapper.xml文件

    public interface BlogMapper {
        //插入数据
        int addBlog(Blog blog);
    }
    
    <?xml version="1.0" encoding="UTF8"?>
    <!DOCTYPE mapper
            PUBLIC "-//mybatis.org//DTD mapper 3.0//EN"
            "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
    <mapper namespace="com.kuang.dao.BlogMapper">
    
        <insert id="addBlog" parameterType="blog">
            insert into mybatis.blog (id, title, author, create_time, views)
            values (#{id},#{title},#{author},#{create_time},#{views});
        </insert>
    
    </mapper>
    
  4. 测试

    @Test
    public void test() {
        SqlSession sqlSession = MybatisUtils.getSqlSession();
        BlogMapper mapper = sqlSession.getMapper(BlogMapper.class);
        mapper.addBlog(new Blog(IDutils.getId(),"我的博客","张三",new Date(),999));
        sqlSession.close();
    }
    

    这里编写了一个生成随机数的类:

    public class IDutils {
        public static String getId() {
            return UUID.randomUUID().toString().replaceAll("-","");
        }
    }
    

if语句

这条语句提供了一种可选的查找文本功能。如果没有传入“title”,那么表中所有数据都会查询出来;如果传入“title”,那么就会执行if语句的条件。

public interface BlogMapper {
	//查找所有博客
    List<Blog> getBlog(Map map);
}
<mapper namespace="com.kuang.dao.BlogMapper">
    <select id="getBlog" parameterType="map" resultType="blog">
        select * from mybatis.blog where 1=1
        <if test="title != null">
            and title = #{title}
        </if>
    </select>
</mapper>
@Test
public void test2() {
    SqlSession sqlSession = MybatisUtils.getSqlSession();
    BlogMapper mapper = sqlSession.getMapper(BlogMapper.class);
    Map<String,String> map = new HashMap<>();
    //加了title,就会执行if语句
    map.put("title","java如此简单");
    List<Blog> blog = mapper.getBlog(map);
    for (Blog blog1 : blog) {
        System.out.println(blog1);
    }
    sqlSession.close();
}

choose(when, otherwise)

相当于java中的 switch case 语句。
只会走其中一个语句。

<select id="getBlogChoose" parameterType="map" resultType="blog">
    select * from mybatis.blog where
    <choose>
        <when test="title != null">
            title = #{title}
        </when>
        <when test="author != null">
            author = #{author}
        </when>
        <otherwise>
            views = #{views}
        </otherwise>
    </choose>
</select>

trim(where,set)

  • set
    用于动态更新语句的类似解决方案叫做 set。set 元素可以用于动态包含需要更新的列,忽略其它不更新的列。
    set 元素会动态地在行首插入 SET 关键字,并会删掉额外的逗号。

    <update id="updateBlog" parameterType="map">
        update mybatis.blog
        <set>
            <if test="title != null">
                title = #{title},
            </if>
            <if test="author != null">
                author = #{author}
            </if>
        </set>
        where id = #{id}
    </update>
    
  • where
    where 元素只会在子元素返回任何内容的情况下才插入 “WHERE” 子句。而且,若子句的开头为 “AND” 或 “OR”,where 元素也会将它们去除。
    意思就是,有条件才执行where,没有条件就不执行;若第一个条件不成立,第二个条件成立,那么第二个条件前面的and会被删除。

    上面if元素的程序中,where后面跟“1=1”是不正规的。如果不使用where标签,这样写是有问题的,因为会存在第一个条件不成立,第二个条件成立的情况,那么SQL拼接就是错误的。

    <mapper namespace="com.kuang.dao.BlogMapper">
        <select id="getBlog" parameterType="map" resultType="blog">
            select * from mybatis.blog where
            <if test="title != null">
                title = #{title}
            </if>
            <if test="anthor != null">
                and author = #{author}
            </if>
        </select>
    </mapper>
    

    在这里插入图片描述
    where可以很智能地拼接后面的条件
    1. 当什么条件也不传或者条件都不成立,where就不会拼接在sql后面
    2. 当第一个条件成立,拼接上where title = #{title}
    3. 当第一个和第二个条件都成立,拼接上where title = #{title} and author = #{author}
    4. 当第一个条件不成立,第二个条件成立,and不会拼接上去

    <select id="getBlog" parameterType="map" resultType="blog">
        select * from mybatis.blog
        <where>
            <if test="title != null">
                and title = #{title}
            </if>
            <if test="author != null">
                and author = #{author}
            </if>
        </where>
    </select>
    

如果 where 和 set 元素与你期望的不太一样,你也可以通过自定义 trim 元素来定制 where 和 set 元素的功能。

where 元素等价的自定义 trim 元素为:

<trim prefix="WHERE" prefixOverrides="AND |OR ">
  ...
</trim>

set 元素等价的自定义 trim 元素为:

<trim prefix="SET" suffixOverrides=",">
  ...
</trim>

SQL片段

有时候,我们可能会将一些功能的部分抽取出来,方便复用!

1. 使用SQL标签抽取公共的部分

<sql id="if-title-author">
    <if test="title != null">
        title = #{title}
    </if>
    <if test="author != null">
        and author = #{author}
    </if>
</sql>

2. 在需要使用的地方加上include标签引用即可

<select id="queryBlogIF" parameterType="map" resultType="com.kuang.pojo.Blog">
    select  * from mybatis.blog
    <where>
        <include refid="if-title-author"></include>
    </where>
</select>

注意事项:
最好基于单表来定义SQL片段!
不要存在where标签。

Foreach

动态 SQL 的另一个常见使用场景是对集合进行遍历(尤其是在构建 IN 条件语句的时候)。

<select id="selectPostIn" resultType="domain.blog.Post">
  SELECT *
  FROM POST P
  <where>
    <foreach item="item" index="index" collection="list"
        open="ID in (" separator="," close=")" nullable="true">
          #{item}
    </foreach>
  </where>
</select>

foreach 元素的功能非常强大,它允许你指定一个集合,声明可以在元素体内使用的集合项(item)和索引(index)变量。它也允许你指定开头与结尾的字符串以及集合项迭代之间的分隔符。这个元素也不会错误地添加多余的分隔符,看它多智能!

提示:你可以将任何可迭代对象(如 List、Set 等)、Map 对象或者数组对象作为集合参数传递给 foreach。当使用可迭代对象或者数组时,index 是当前迭代的序号,item 的值是本次迭代获取到的元素。当使用 Map 对象(或者 Map.Entry 对象的集合)时,index 是键,item 是值。

public interface BlogMapper {
    List<Blog> getBlogForeach(Map map);
}
<select id="getBlogForeach" parameterType="map" resultType="blog">
    select * from mybatis.blog
    <where>
        <foreach collection="ids" item="id" open="(" separator=" or" close=")">
            id = #{id}
        </foreach>
    </where>
</select>
@Test
public void test4() {
    SqlSession sqlSession = MybatisUtils.getSqlSession();
    BlogMapper mapper = sqlSession.getMapper(BlogMapper.class);
    ArrayList<Integer> ids = new ArrayList<>();
    ids.add(1);
    ids.add(2);
    ids.add(3);
    Map map = new HashMap<>();
    map.put("ids",ids);
    List<Blog> blogs = mapper.getBlogForeach(map);
    for (Blog blog : blogs) {
        System.out.println(blog);
    }
    sqlSession.close();
}

所谓的动态SQL,本质还是SQL语句,只是我们可以在SQL层面,去执行一个逻辑代码。

11. 缓存

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

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

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

Mybatis系统中默认定义了两级缓存:一级缓存和二级缓存。

默认情况下,只有一级缓存开启。(SqlSession级别的缓存,也称为本地缓存)
二级缓存需要手动开启和配置,他是基于namespace级别的缓存。

为了提高扩展性。Mybatis定义了缓存接口Cache。我们可以通过实现Cache接口来自定义二级缓存

一级缓存

  • 一级缓存也叫本地缓存:SqlSession
    • 与数据库同一次会话期间查询到的数据会放在本地缓存中
    • 以后如果需要获取相同的数据,直接从缓存中拿,不需要再去访问数据库

默认情况下,只启用了本地的会话缓存,它仅仅对一个会话中的数据进行缓存。

映射语句文件中的所有 select 语句的结果将会被缓存。

映射语句文件中的所有 insert、update 和 delete 语句会刷新缓存。

缓存会使用最近最少使用算法(LRU, Least Recently Used)算法来清除不需要的缓存。

缓存不会定时进行刷新(也就是说,没有刷新间隔)。

缓存会保存列表或对象(无论查询方法返回哪种)的 1024 个引用。

缓存会被视为读/写缓存,这意味着获取到的对象并不是共享的,可以安全地被调用者修改,而不干扰其他调用者或线程所做的潜在修改。

测试

@Test
public void getUserById() {
    SqlSession sqlSession = MybatisUtils.getSqlSession();
    UserDao mapper = sqlSession.getMapper(UserDao.class);

    User user = mapper.getUserById(1);
    System.out.println(user);
    User user2 = mapper.getUserById(1);
    System.out.println(user);
    System.out.println("=========================");
    System.out.println(user == user2);

    sqlSession.close();
}

测试在一个SqlSession中查询两个相同的记录,两个对象连地址都一样,说明第二次查询走的缓存。

缓存失效的情况:
1.查询不同的东西
2.增删改操作,可能会改变原来的数据,所以会刷新缓存
3.查询不同的Mapper.xml
4.手动清理缓存(sqlSession.clearCache()

小结:一级缓存默认是开启的,只在一次SqlSession中有效,也就是拿到连接到关闭连接这个区间段!

二级缓存

  • 二级缓存也叫全局缓存,一级缓存作用域太低了,所以诞生了二级缓存
  • 基于namespace级别的缓存,一个名称空间,对应一个二级缓存
  • 工作机制
    一个会话查询一条数据,这个数据就会被放在当前会话的一级缓存中
    如果当前会话关闭了,这个会话对应的一级缓存就没了;但是我们想要的是,会话关闭了,一级缓存中的数据被保存到二级缓存中;
    新的会话查询信息,就可以从二级缓存中获取内容
    不同的mapper查出的数据会放在自己对应的缓存(map)中

步骤:
1.开启全局缓存

<!--显示的开启全局缓存-->
<setting name="cacheEnabled" value="true"/>

2.在要使用二级缓存的Mapper中开启

<!--在当前Mapper.xml中使用二级缓存-->
<cache/>

也可以自定义参数

<cache
  eviction="FIFO"
  flushInterval="60000"
  size="512"
  readOnly="true"/>

这个更高级的配置创建了一个 FIFO 缓存,每隔 60 秒刷新,最多可以存储结果对象或列表的 512 个引用,而且返回的对象被认为是只读的,因此对它们进行修改可能会在不同线程中的调用者产生冲突。

可用的清除策略有:

  • LRU – 最近最少使用:移除最长时间不被使用的对象。
  • FIFO – 先进先出:按对象进入缓存的顺序来移除它们。
  • SOFT – 软引用:基于垃圾回收器状态和软引用规则移除对象。
  • WEAK – 弱引用:更积极地基于垃圾收集器状态和弱引用规则移除对象。
    默认的清除策略是 LRU。

测试
问题:我们需要将实体类序列化!否则会报错
Cause: java.io.NotSerializableException: com.kuang.pojo.User

小结:
只要开启了二级缓存,在同一个Mapper下就有效。
所有的数据都会先放在一级缓存中。
只有当会话提交,或者关闭的时候,才会提交到二级缓存中。

缓存顺序:先看二级缓存中有没有;再看一级缓存中有没有;查询数据库。

自定义缓存-ehcache

Ehcache是一种广泛使用的开源Java分布式缓存。主要面向通用缓存

要在程序中使用ehcache,先要导包

<dependency>
    <groupId>org.mybatis.caches</groupId>
    <artifactId>mybatis-ehcache</artifactId>
    <version>1.1.0</version>
</dependency>

在mapper中指定使用我们的ehcache缓存实现

<cache type="org.mybatis.caches.ehcache.EhcacheCache"/>
  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值