mybatis

本文是MyBatis的全面教程,涵盖第一个MyBatis程序搭建、增删改查操作、配置解析、结果集映射、日志、分页查询、注解开发、多对一与一对多处理、动态SQL以及缓存等内容,详细介绍了各部分的实现方法和注意事项。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

一、第一个Mybatis程序

1.1 创建数据库

CREATE DATABASE `mybatis`;
USE `mybatis`;
-- ----------------------------
-- Table structure for user
-- ----------------------------
DROP TABLE IF EXISTS `user`;
CREATE TABLE `user` (
  `id` int(15) NOT NULL,
  `name` varchar(30) NOT NULL,
  `pwd` varchar(30) DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

-- ----------------------------
-- Records of user
-- ----------------------------
INSERT INTO `user` VALUES ('1', '张三', '123456');
INSERT INTO `user` VALUES ('2', '李四', '123456');
INSERT INTO `user` VALUES ('3', '王五', '123456');

1.2 搭建环境&编写代码

1.2.1 导入Maven依赖

<dependencies>
        <!--mysql-->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>8.0.15</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>
        </dependency>
</dependencies>

1.2.2 Mybatis核心配置文件

<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=UTF8&amp;serverTimezone=UTC"/>
                <property name="username" value="root"/>
                <property name="password" value="root"/>
            </dataSource>
        </environment>
    </environments>
    <mappers>
        <mapper resource="com/mybatis/mapper/UserMapper.xml"/>
    </mappers>
</configuration>

1.2.3 Mybatis工具类

public class MybatisUtils {
    private static SqlSessionFactory sqlSessionFactory;
    static {
        String resource = "mybatis-config.xml";
        InputStream inputStream = null;
        try {
            //第一步:获取SqlSessionFactory对象
            inputStream = Resources.getResourceAsStream(resource);
            sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    //第二步:获取sqlSession示例
    public static SqlSession getSqlSession(){
        return sqlSessionFactory.openSession();
    }
}

1.2.4编写代码

  • 实体类

    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;
        }
    
        @Override
        public String toString() {
            return "User{" +
                    "id=" + id +
                    ", name='" + name + '\'' +
                    ", 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;
        }
    }
    
  • Mapper接口

    public interface UserMapper {
        List<User> getUserList();
    }
    
  • 接口实现类

    public class UserMapperImpl implements UserMapper{
        public List<User> getUserList() {
            return getUserList();
        }
    }
    
  • 接口实现类配置文件

    <?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 绑定mapper接口-->
    <mapper namespace="com.mybatis.mapper.UserMapper">
    
        <select id="getUserList" resultType="com.mybatis.pojo.User">
            select * from user
        </select>
    
    </mapper>
    

1.3 测试

1.3.1 添加资源导出设置

<build>
        <resources>
            <resource>
                <directory>src/main/java</directory>
                <includes>
                    <include>**/*.xml</include>
                </includes>
                <filtering>true</filtering>
            </resource>
            <resource>
                <directory>src/main/resources</directory>
                <includes>
                    <include>**/*.properties</include>
                    <include>**/*.xml</include>
                </includes>
                <filtering>true</filtering>
            </resource>
        </resources>
    </build>

1.3.2 测试类

public class UserMapperTest {  
    @Test
    public void test(){
        //第一步:获取sqlSession对象
        SqlSession sqlSession= MybatisUtils.getSqlSession();
        //第二步:执行SQL
        UserMapper userMapper=sqlSession.getMapper(UserMapper.class);
        List<User> userList=userMapper.getUserList();

        for (User user : userList) {
            System.out.println(user);
        }
        //第三步:关闭sqlSession
        sqlSession.close();
    }
}

二、增删改查

  • namespace包名与mapper接口的包名保持一致
  • id:对应于namespace中的方法名
  • parameterType:参数类型
  • resultType:返回类型

2.1 编写接口

    int insertUser(User user);
    int updateUserById(User user);
    User selectUserById(int id);
    int deleteUserById(int id);

2.2 编写对应Mapper中sql语句

    <insert id="insertUser" parameterType="com.mybatis.pojo.User" >
        insert into user (id,name,pwd) values (#{id},#{name},#{pwd})
    </insert>
    <update id="updateUserById" parameterType="com.mybatis.pojo.User">
        update user set name=#{name},pwd=#{pwd} where id=#{id}
    </update>
    <select id="selectUserById" resultType="com.mybatis.pojo.User">
        select * from user where id=#{id}
    </select>
    <delete id="deleteUserById" parameterType="int">
        delete from user where id=#{id}
    </delete>

2.3 测试

    @Test
    public void insertUserTest() {
        SqlSession sqlSession=MybatisUtils.getSqlSession();
        UserMapper userMapper=sqlSession.getMapper(UserMapper.class);

        userMapper.insertUser(new User(4,"user4","2333"));
        //提交事务
        sqlSession.commit();
        sqlSession.close();
    }
    @Test
    public void updateUserByIdTest() {
        SqlSession sqlSession=MybatisUtils.getSqlSession();
        UserMapper userMapper=sqlSession.getMapper(UserMapper.class);
        userMapper.updateUserById(new User(4,"user4","3333"));
        //提交事务
        sqlSession.commit();
        sqlSession.close();
    }
    @Test
    public void selectUserByIdTest() {
        SqlSession sqlSession=MybatisUtils.getSqlSession();
        UserMapper userMapper=sqlSession.getMapper(UserMapper.class);
        User user=userMapper.selectUserById(4);
        System.out.println(user);
        sqlSession.close();

    }
    @Test
    public void deleteUserByIdTest() {
        SqlSession sqlSession=MybatisUtils.getSqlSession();
        UserMapper userMapper=sqlSession.getMapper(UserMapper.class);
        userMapper.deleteUserById(4);
        //提交事务
        sqlSession.commit();
        sqlSession.close();
    }

2.4 使用Map

2.4.1 查询

  1. 接口
	User getUserByMap(Map<String,Object> map);
  1. 对应Mapper中sql语句
    <select id="getUserByMap" parameterType="map" resultType="com.mybatis.pojo.User">
        select * from user where id=#{userId}
    </select>
  1. 测试
    @Test
    public void getUserByMap(){
        SqlSession sqlSession=MybatisUtils.getSqlSession();
        UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
        HashMap<String, Object> map = new HashMap<>();
        map.put("userId",1);
        User user = userMapper.getUserByMap(map);
        System.out.println(user);
        sqlSession.close();
    }

2.4.1 更新

  1. 接口
	int updateUserByMap(Map<String,Object> map);
  1. 对应Mapper中SQL语句
    <update id="updateUserByMap" parameterType="map">
        update user set name=#{userName} where id=#{userId}
    </update>
  1. 测试
    @Test
    public void updateUserByMap(){
        SqlSession sqlSession = MybatisUtils.getSqlSession();
        UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
        HashMap<String, Object> map = new HashMap<>();
        map.put("userId","1");
        map.put("userName","user1");
        int i = userMapper.updateUserByMap(map);
        sqlSession.commit();
        sqlSession.close();
    }

2.5 模糊查询

  1. Java代码执行时,使用通配符“%”。

    SQL语句

    <select id="getUserLike" parameterType="String" resultType="com.mybatis.pojo.User">
        select * from USER where name like #{firstName};
    </select>

​ Java查询

	List<User> userList = userMapper.getUserLike("%user%");
  1. 在SQL中拼接通配符%。

    SQL语句

    <select id="getUserLike" parameterType="String" resultType="com.mybatis.pojo.User">
        select * from USER where name like "%"#{firstName}"%";
    </select>
	 Java查询
    List<User> userList = userMapper.getUserLike("user");

三、Mybatis配置解析

MyBatis 的配置文件包含了会深深影响 MyBatis 行为的设置和属性信息。 配置文档的顶层结构如下:

configuration(配置)

3.1 环境配置(environments)

  • MyBatis 可以配置成适应多种环境,例如,开发、测试和生产环境需要有不同的配置;但每个 SqlSessionFactory 实例只能选择一种环境。
  • 默认使用的环境 ID(比如:default=“development”)。
  • 每个 environment 元素定义的环境 ID(比如:id=“development”)。
  • 事务管理器的配置(比如:type="[JDBC|MANAGED]")。
  • JDBC – 这个配置直接使用了 JDBC 的提交和回滚设施,它依赖从数据源获得的连接来管理事务作用域
  • 数据源的配置(比如:type="[UNPOOLED|POOLED|JNDI]")。
  • POOLED– 这种数据源的实现利用“池”的概念将 JDBC 连接对象组织起来,避免了创建新的连接实例时所必需的初始化和认证时间,能使并发 Web 应用快速响应请求

3.2 属性(properties)

属性可以在外部进行配置,并可以进行动态替换;既可以在典型的 Java 属性文件中配置这些属性,也可以在 properties 元素的子元素中设置。

    <properties resource="config.properties"/>

编写配置文件config.properties

driver=com.mysql.jdbc.Driver
url=jdbc:mysql://localhost:3306/mybatis?useSSl=true&useUnicode=true&characterEncoding=UTF8&serverTimezone=UTC
username=root
password=root

在核心配置文件mybatis-config.xml中映射

	<properties resource="config.properties">
        <property name="username" value="toot"/>
        <property name="password" value="F2Fa3!33TYyg"/>
    </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>
  • 如果一个属性在不只一个地方进行了配置,那么,MyBatis 将按照下面的顺序来加载:

    • 首先读取在 properties 元素体内指定的属性。
    • 然后根据 properties 元素中的 resource 属性读取类路径下属性文件,或根据 url 属性指定的路径读取属性文件,并覆盖之前读取过的同名属性。
    • 最后读取作为方法参数传递的属性,并覆盖之前读取过的同名属性。

    因此,通过方法参数传递的属性具有最高优先级,resource/url 属性中指定的配置文件次之,最低优先级的则是 properties 元素中指定的属性。

3.3 类型别名(typeAliases)

类型别名可为 Java 类型设置一个缩写名字。 它仅用于 XML 配置,意在降低冗余的全限定类名书写。

有两种方式,一是直接定义对象别名

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

对应SQL语句

	<select id="getUserList" resultType="User">
        select * from user
    </select>

也可以指定包名,MyBatis 会在包名下面搜索需要的 Java Bean;在没有注解的情况下,会使用 Bean 的首字母小写的非限定类名来作为它的别名。

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

对应SQL语句

    <select id="getUserList" resultType="user">
        select * from user
    </select>

在指定包名的情况下,也可以通过注解为Bean定义别名。

@Alias("myUser")
public class User {
    ...
}

3.4 设置(settings)

一个配置完整的 settings 元素的示例如下:- 具体说明

<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>

3.5 映射器(mappers)

作用:注册绑定哦我们的Mapper文件

方式一:使用相对于类路径的资源引用

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

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

<mappers>
  <package name="com.mybatis.mapper"/>
</mappers>

注意:

  • 接口与它的Mapper配置文件必须同名
  • 接口与它的Mapper配置文件必须在同一个包下。

方式三:使用映射器接口实现类的完全限定类名

<mappers>
  <mapper class="com.mybatis.mapper.UserMapper"/>
</mappers>

注意:

  • 接口与它的Mapper配置文件必须同名(报错:Invalid bound statement (not found))
  • 接口与它的Mapper配置文件必须在同一个包下。

方式四:使用完全限定资源定位符(URL)

<mappers>
  <mapper url="file:///var/mappers/AuthorMapper.xml"/>
</mappers>

3.6 作用域(Scope)和生命周期

不同作用域和生命周期类别是至关重要的,错误的使用会导致非常严重的并发问题。

SqlSessionFactoryBuilder

  • 创建工厂sqlSessionFactory, 创建了 SqlSessionFactory以后,就不再需要它了;
  • SqlSessionFactoryBuilder 实例的最佳作用域是方法作用域(也就是局部方法变量)。

sqlSessionFactory

  • sqlSessionFactory被创建就应该在应用的运行期间一直存在
  • SqlSessionFactory 的最佳作用域是应用作用域,最简单的就是使用单例模式或者静态单例模式。

SqlSession

  • 每个线程都应该有它自己的 SqlSession 实例;
  • SqlSession 的实例不是线程安全的,因此是不能被共享的,所以它的最佳的作用域是请求或方法作用域;
  • 关闭操作很重要,为了确保每次都能执行关闭操作,你应该把这个关闭操作放到 finally 块中。

下面的示例就是一个确保 SqlSession 关闭的标准模式:

try (SqlSession session = sqlSessionFactory.openSession()) {
  // 你的应用逻辑代码
}catch (IOException e) {
    e.printStackTrace();
}finally{
    session.close();
}

四、ResultMap结果集映射

4.1 问题描述

当出现属性名与字段名不一致问题时,需要使用ResultMap。

JavaBean属性

public class User {
    private int id;
    private String name;
    private String password;
}

数据库字段

CREATE TABLE `user` (
  `id` int(15) NOT NULL,
  `name` varchar(30) NOT NULL,
  `pwd` varchar(30) DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

其中,JavaBean密码属性为“password”,数据库字段名为“pwd”。

执行查询语句

    <select id="selectUserById" resultType="com.mybatis.pojo.User">
        select * from user where id=#{id}
    </select>

返回结果password为空。

User{id=1, name='user1', password='null'}

简单解决方案:

  • 起别名
<select id="selectUserById" resultType="com.mybatis.pojo.User">
    select id,name,pwd as password from user where id=#{id}
</select>

4.2 简单ResultMap结果集映射

作用:结果集映射

id	 -> id
name -> name
pwd  -> password
	<resultMap id="UserMap" type="user">
        <!-- column:数据库字段名 property:实体类属性-->
        <!-- 一致的字段名与属性之间无需进行映射-->
        <!-- <result column="id" property="id"/>-->
        <!-- <result column="name" property="name"/>-->
        <result column="pwd" property="password"/>
    </resultMap>
    <!--    select id,name,pwd as password from user where id=#{id}-->
    <select id="selectUserById" resultMap="UserMap">
        select * from user where id=#{id}
    </select>

注意:select中的resulType需要更改为对应的resultMap,否则会报错。

Cause: org.apache.ibatis.type.TypeException: Could not resolve type alias ‘UserMap’.
Cause: java.lang.ClassNotFoundException: Cannot find class: UserMap
  • resultMap 元素是 MyBatis 中最重要最强大的元素;
  • ResultMap 的设计思想是,对简单的语句做到零配置,对于复杂一点的语句,只需要描述语句之间的关系;
  • 可以不用显式地配置ResultMap ,即一致的字段名与属性之间无需进行映射

五、日志

5.1 日志工程

Mybatis 通过使用内置的日志工厂提供日志功能。

STDOUT_LOGGING标准日志输出示例

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

日志结果:

Opening JDBC Connection
Created connection 443721024.
Setting autocommit to false on JDBC Connection [com.mysql.cj.jdbc.ConnectionImpl@1a72a540]
> Preparing: select * from user where id=?
> Parameters: 1(Integer)
<== Columns: id, name, pwd
<== Row: 1, user1, 123456
<== Total: 1
User{id=1, name=‘user1’, password=‘123456’}
Resetting autocommit to true on JDBC Connection [com.mysql.cj.jdbc.ConnectionImpl@1a72a540]
Closing JDBC Connection [com.mysql.cj.jdbc.ConnectionImpl@1a72a540]
Returned connection 443721024 to pool.

5.2 Log4J

  • Log4j是Apache的一个开源项目,通过使用Log4j,我们可以控制日志信息输送的目的地是控制台、文件等;
  • 可以控制每一条日志的输出格式与日志信息的级别,
  • 可以通过一个配置文件来灵活地进行配置,而不需要修改应用的代码。
  1. 导入Log4J包
<dependency>
    <groupId>log4j</groupId>
    <artifactId>log4j</artifactId>
    <version>1.2.17</version>
</dependency>
  1. 配置log4j.properties
#将等级为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/log4J.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
  1. 配置log4j为日志控制
<settings>
    <setting name="logImpl" value="Log4J"/>
</settings>
  1. 日志输出

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-JOp2bIbK-1610295207513)(C:\Users\zhoubao\AppData\Roaming\Typora\typora-user-images\image-20201215211241685.png)]

注意:

如果出现报错

Cause: java.lang.NoClassDefFoundError: org/apache/log4j/Priority

说明是log4J包没有正确导入maven项目,如果已经添加依赖,则检查maven项目是否同步。

六、分页查询

6.1Limit分页

基础语法

select * from tablename order by orderfield desc/asc limit startIndex, pageSize;
select ... limit n 等价于 select ... limit 0,n
  1. 定义接口
List<User> selectUserByLimit(Map<String,Integer> map);
  1. mapper映射
<select id="selectUserByLimit" parameterType="map" resultMap="UserMap">
    select * from user limit #{startIndex},#{pageSize}
</select>
  1. 测试
    @Test
    public void selectUserByLimitTest(){
        SqlSession sqlSession = MybatisUtils.getSqlSession();
        UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
        Map<String,Integer> map=new HashMap<>();
        map.put("startIndex",2);
        map.put("pageSize",2);
        List<User> userList = userMapper.selectUserByLimit(map);
        for (User user : userList) {
            System.out.println(user);
        }
        sqlSession.close();
    }
  1. 返回结果

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-6pCAn9mq-1610295207515)(C:\Users\zhoubao\AppData\Roaming\Typora\typora-user-images\image-20201215214803515.png)]

6.2 RowBounds分页

  <E> java.util.List<E> selectList(java.lang.String s, java.lang.Object o, org.apache.ibatis.session.RowBounds rowBounds);
  1. 定义接口
List<User> selectUserByRowBounds();
  1. mapper映射文件
    <select id="selectUserByRowBounds" resultMap="UserMap">
        select * from user
    </select>
  1. 测试
    @Test
    public void selectUserByRowBoundsTese(){
        SqlSession sqlSession = MybatisUtils.getSqlSession();

        RowBounds rowBounds = new RowBounds(2,2);
        List<User> userList = sqlSession.selectList("com.mybatis.mapper.UserMapper.selectUserByRowBounds",null,rowBounds);
        for (User user : userList) {
            System.out.println(user);
        }
        sqlSession.close();
    }

6.3 分页插件

七、使用注解开发

7.1 注解开发

  1. 定义接口
    @Select("select id, name,pwd as password from user")
    List<User> getUser();
  1. 绑定接口
    <mappers>
        <mapper class="com.mybatis.mapper.UserMapper"/>
    </mappers>
  1. 测试
    @Test
    public void test() {

        //第一步:获取sqlSession对象
        SqlSession sqlSession = MybatisUtils.getSqlSession();
        //第二步:执行SQL
        UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
        List<User> userList = userMapper.getUser();

        for (User user : userList) {
            System.out.println(user);
        }
        //第三步:关闭sqlSession
        sqlSession.close();
    }
  1. 返回结果

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-QtEf6w2I-1610295207516)(C:\Users\zhoubao\AppData\Roaming\Typora\typora-user-images\image-20201216214435940.png)]

7.2 CURD

  1. 设置事务自动提交
	//获取sqlSession示例
    public static SqlSession getSqlSession(){
        return sqlSessionFactory.openSession(true);
    }
  1. 绑定接口
<mappers>
    <mapper class="com.mybatis.mapper.UserMapper"/>
</mappers>
  1. 接口定义
//select
//参数使用@Param()传递
@Select("select id,name, pwd as password from user where id=#{id}")
User getUserById(@Param("id") int id);
//insert
@Insert("insert into user(id,name,pwd) values(#{id},#{name},#{password})")
int addUser(User user);
//update
@Update("update user set name=#{name},pwd=#{password} where id=#{id}")
int updateUser(User user);
//delete
@Delete("delete from user where id=#{id}")
int deleteUser(@Param("id") int id);
  1. 测试
//select
User user = userMapper.getUserById(1);
//insert
int result = userMapper.addUser(new User(6,"user6","6"));
//update
int result =userMapper.updateUser(new User(6,"user6","password6"));
//delete
int result=userMapper.deleteUser(6);

注意:必须使用绑定接口,否则报错:

Type interface com.mybatis.mapper.UserMapper is not known to the MapperRegistry.

八、Lombok 插件

  • Project Lombok is a java library that automatically plugs into your editor and build tools, spicing up your java.

  • Never write another getter or equals method again, with one annotation your class has a fully featured builder, Automate your logging variables, and much more.

    1.安装Lombok 插件

    • File-Setting-Plugins-Lombok install,并在installed中设置为可用。
    image-20201219191555579

    2.导入jar包

<dependency>
    <groupId>org.projectlombok</groupId>
    <artifactId>lombok</artifactId>
    <version>1.18.12</version>
</dependency>
  1. 常见注释及意义
@Getter and @Setter
    生成Getter与Setter方法
@FieldNameConstants
@ToString
    生成ToString方法
@EqualsAndHashCode
    生成Equals与HashCode
@AllArgsConstructor, @RequiredArgsConstructor and @NoArgsConstructor
    AllArgsConstructor:生成所有参数构造;NoArgsConstructor:生成无参构造
@Log, @Log4j, @Log4j2, @Slf4j, @XSlf4j, @CommonsLog, @JBossLog, @Flogger, @CustomLog
@Data
    自动生成无参构造、Getter、Setter、toString、
@Builder
@SuperBuilder
@Singular
@Delegate
@Value
@Accessors
@Wither
@With
@SneakyThrows
  1. 使用
@Data
@AllArgsConstructor
@NoArgsConstructor
public class User {

    private int id;
    private String name;
    private String password;

}
  1. 结果
image-20201220135145622

九、多对一&一对多

association– 一个复杂类型的关联;许多结果将包装成这种类型

  • 嵌套结果映射 – 关联可以是 resultMap 元素,或是对其它结果映射的引用
  • javaType - 指定实体类中属性的类别

collection– 一个复杂类型的集合

  • 嵌套结果映射 – 集合可以是 resultMap 元素,或是对其它结果映射的引用
  • ofType - 指定List或者集合中的pojo对象

9.1 多对一处理

9.1.1 搭建环境

  1. 导入Lombok
<dependency>
    <groupId>org.projectlombok</groupId>
    <artifactId>lombok</artifactId>
    <version>1.18.12</version>
</dependency>
  1. 创建数据表
CREATE TABLE `teacher` (
  `id` int(15) NOT NULL,
  `name` varchar(30) NOT 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) not null,
    `tid` int(10) not 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','student1','1');
insert into `student` (`id`,`name`,`tid`) values ('2','student2','1');
insert into `student` (`id`,`name`,`tid`) values ('3','student3','1');
insert into `student` (`id`,`name`,`tid`) values ('4','student4','1');
insert into `student` (`id`,`name`,`tid`) values ('5','student5','1');
  1. 创建实体类
@Data
@NoArgsConstructor
@AllArgsConstructor
public class Teacher {
    private int id;
    private String name;
}
@Data
@NoArgsConstructor
@AllArgsConstructor
public class Student {
    private int id;
    private String name;
    //多对一,映射老师实体类
    private Teacher teacher;
}
  1. 创建接口
public interface StudentMapper {}
public interface TeacherMapper {}
  1. 创建.xml
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
        PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<!--StudentMapper-->
<mapper namespace="com.mybatis.mapper.StudentMapper">
</mapper>
<?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">
<!--TeacherMapper-->
<mapper namespace="com.mybatis.mapper.TeacherMapper">
</mapper>
  1. 绑定Mapper接口
    <mappers>
        <mapper resource="com/mybatis/mapper/StudentMapper.xml"/>
        <mapper resource="com/mybatis/mapper/TeacherMapper.xml"/>
    </mappers>
  1. 测试环境

9.1.2 按照查询嵌套处理

MySQL处理多对一关系

  • 嵌套子查询
select id student_id,name studentstudent_name,tid teacher_id from student 
where tid 
in(select id from teacher where id='1');
<select id="getStudent" resultMap="student_teacher_map">
    select * from student
</select>

<resultMap id="student_teacher_map" type="student">
    <result property="id" column="id"/>
    <result property="name" column="name"/>
    <association property="teacher" column="tid" javaType="Teacher" select="getTeacher"/>
</resultMap>

<select id="getTeacher" parameterType="int" resultType="teacher">
    select * from teacher where id=#{tid}
</select>

9.1.3 按照结果嵌套处理

MySQL处理多对一关系

  • 联表查询
select s.id student_id,s.name student_name,t.name teacher_name 
from student s,teacher t 
where s.tid=t.id and t.id=1;
 <select id="getStudent" resultMap="student_teacher_map">
        select s.id student_id,s.name student_name,t.id teacher_id,t.name teacher_name 
        from student s,teacher t 
        where s.tid=t.id
</select>
<resultMap id="student_teacher_map" type="student">
    <result property="id" column="student_id"/>
    <result property="name" column="student_name"/>
    <association property="teacher" javaType="Teacher">
        <result property="id" column="teacher_id"/>
        <result property="name" column="teacher_name"/>
    </association>
</resultMap>

9.2 一对多处理

9.2.1 搭建环境

  1. 创建实体类
@Data
@AllArgsConstructor
@NoArgsConstructor
public class Student_one2more {
    private int id;
    private String name;
    private int tid;
}
@Data
@AllArgsConstructor
@NoArgsConstructor
public class Teacher_one2more {
    private int id;
    private String name;
    private List<String> students;
}

9.2.2 按照查询嵌套处理

    <select id="getTeacher" resultMap="teacher_student_map">
        select id teacher_id,name teacher_name from teacher where id=#{id};
    </select>

    <resultMap id="teacher_student_map" type="teacher_one2more">
        <result property="id" column="teacher_id"/>
        <result property="name" column="teacher_name"/>
        <collection property="students" javaType="ArrayList" ofType="student" select="getStudent" column="teacher_id"/>
    </resultMap>
    <select id="getStudent" resultType="student_one2more">
        select * from student where tid=#{teacher_id};
    </select>

9.2.3 按照结果嵌套处理

MySQL处理多对一关系

  • 联表查询
select t.id teacher_id,t.name teacher_name,s.id student_id,s.name student_name
from teacher t,student s
where t.id=s.tid and t.id=#{id};
<select id="getTeacher" resultMap="teacher_student_map">
    select t.id teacher_id,t.name teacher_name,s.id student_id,s.name student_name
    from teacher t,student s
    where t.id=s.tid and t.id=#{id};
</select>

<resultMap id="teacher_student_map" type="Teacher_one2more">
    <result property="id" column="teacher_id"/>
    <result property="name" column="teacher_name"/>
    <collection property="students" ofType="Student_one2more">
        <result property="id" column="student_id"/>
        <result property="name" column="student_name"/>
        <result property="tid" column="teacher_id"/>
    </collection>
</resultMap>

十、动态SQL

动态SQL元素种类:

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

10.1 动态SQL-搭建环境

  1. 创建数据库
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. 创建工具类
public class MybatisUtils {
    private static SqlSessionFactory sqlSessionFactory;

    static {
        try {
            String resource = "mybatis-config.xml";

            //第一步:获取SqlSessionFactory对象
            InputStream inputStream = Resources.getResourceAsStream(resource);
            sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    //第二步:获取sqlSession示例
    public static SqlSession getSqlSession() {
        //设置自动提交事务
        return sqlSessionFactory.openSession(true);
    }
}
@SuppressWarnings("all")//抑制警告
public class IdUtils {

    public static String getid(){
        return UUID.randomUUID().toString().replaceAll("-","");
    }
    @Test
    public void test(){
        System.out.println(getid());
    }
}
  1. 创建实体类
@Data
@AllArgsConstructor
@NoArgsConstructor
public class Blog {
    private String id;
    private String title;
    private String author;
    private Date createTime;
    private int views;
}
  1. 创建接口及xml文件
public interface BlogMapper {
    int insertBlog(Blog blog);
}
<?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">
<!--StudentMapper-->
<mapper namespace="com.mybatis.mapper.BlogMapper">
    <insert id="insertBlog" parameterType="blog">
        insert into
        blog (id,title,author,create_time,views)
        values
        (#{id},#{title},#{author},#{createTime},#{views});
    </insert>
</mapper>
  1. 测试
@Test
public void getBlogTest(){
    SqlSession sqlSession = MybatisUtils.getSqlSession();
    BlogMapper blogMapper = sqlSession.getMapper(BlogMapper.class);
    for (int i = 1; i < 4 ;i++) {
        Blog blog=new Blog(IdUtils.getid(),"第"+i+"篇Springboot博客","作者"+i,new Date(),i);
        blogMapper.insertBlog(blog);
        //提交事务

    }
    sqlSession.close();
}

10.2 动态SQL-常用标签

where 标签

  • where 元素只会在子元素返回任何内容的情况下才插入 “WHERE” 子句
  • 若子句的开头为 “AND” 或 “OR”,where 元素也会将它们去除

if 标签

  • 根据条件包含 where 子句的一部分

choose 标签

  • 从多个条件中选择一个使用
  • 有点像 Java 中的 switch 语句

set 标签

  • 用于动态包含需要更新的列,忽略其它不更新的列

  • set 元素会动态地在行首插入 SET 关键字,并会删掉额外的逗号

  • 但不会为set子语句添加逗号

trim 标签

  • 自定义 元素

  • where 元素等价的自定义 trim 元素

    <trim prefix="WHERE" prefixOverrides="AND |OR ">
      ...
    </trim>
    
  • set 元素等价的自定义 trim 元素

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

sql 标签

  • 复用公共的SQL代码
  • 通过引用sql片段,通过refid指定sql片段id

foreach 标签

  • 对集合进行遍历(尤其是在构建 IN 条件语句的时候)

  • 允许指定一个集合,声明可以在元素体内使用的集合项(item)和索引(index)变量

  • 也允许你指定开头与结尾的字符串以及集合项迭代之间的分隔符

  • 示例

    <select id="selectPostIn" resultType="domain.blog.Post">
      SELECT *
      FROM POST P
      WHERE ID in
      <foreach item="item" index="index" collection="list"
          open="(" separator="or" close=")">
            #{item}
      </foreach>
    </select>
    
  • 等价于(当list={1,2,3})

    
    <select id="selectPostIn" resultType="domain.blog.Post">
      SELECT *
      FROM POST P
      WHERE 1=1 and(id =1 or id=2 or id=3);
    </select>
    

10.2.1 if 标签演示

  1. 接口定义
    List<Blog> getBlogByIf(Map map);
  1. SQL语句
<select id="getBlogByIf" parameterType="map" resultType="blog">
    select * from blog
    <where>
        <if test="title != null">
            title like #{title}
        </if>
        <if test="author != null">
            and author like #{author}
        </if>
    </where>
</select>
  1. 测试
@Test
public void getBlogByIf(){
    SqlSession sqlSession = MybatisUtils.getSqlSession();
    BlogMapper blogMapper = sqlSession.getMapper(BlogMapper.class);
    Map<String,String> map=new HashMap<>();
    map.put("title","%Redis%");
    map.put("author","%1%");
    List<Blog> blogs=blogMapper.getBlogByIf(map);
    sqlSession.close();

}

10.2.2 choose 标签演示

  1. 接口定义
List<Blog> getBlogByChoose(Map map);
  1. SQL语句
<select id="getBlogByChoose" parameterType="map" resultType="blog">
    select * from blog
    <where>
        <choose>
            <when test="title != null">
                title like #{title}
            </when>
            <when test="author !=null">
                author like #{author}
            </when>
            <otherwise></otherwise>
        </choose>
    </where>
</select>
  1. 测试
@Test
public void getBlogByChoose(){
    SqlSession sqlSession = MybatisUtils.getSqlSession();
    BlogMapper blogMapper = sqlSession.getMapper(BlogMapper.class);
    Map<String,String> map=new HashMap<>();
    map.put("title","%redis%");
    map.put("author","%1%");
    blogMapper.getBlogByChoose(map);
    sqlSession.close();
}

10.2.3 set 标签演示

  1. 定义接口
int updateBlog(Map map);
  1. SQL语句
    <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>
  1. 测试
@Test
public void updateBlog(){
    SqlSession sqlSession = MybatisUtils.getSqlSession();
    BlogMapper blogMapper = sqlSession.getMapper(BlogMapper.class);

    Map<String,String> map=new HashMap<>();
    map.put("id","aa619b7bc95044d0a45d91778181eaa0");
    map.put("title","第1篇Redis博客1");
    map.put("author","作者1");
    blogMapper.updateBlog(map);
    sqlSession.close();
}

10.2.4 sql 标签演示

  1. 定义sql片段
<sql id="selectBlog">
    select * from blog
</sql>

<sql id="if_title_author_null">
    <if test="title != null">
        title like #{title}
    </if>
    <if test="author != null">
        and author like #{author}
    </if>
</sql>
  1. 引用sql片段
<select id="getBlogByIf" parameterType="map" resultType="blog">
    <include refid="selectBlog"></include>
    <where>
        <include refid="if_title_author_null"></include>
    </where>
</select>

10.2.5 Foreach 标签

  1. 定义接口
   List<Blog> getBlogForeach(Map map);
  1. SQL语句
<select id="getBlogForeach" parameterType="map" resultType="blog">
    select * from blog
    <where>
        <foreach collection="authors" item="author" open="(" separator="or" close=")">
            author=#{author}
        </foreach>
    </where>
</select>
  1. 测试
@Test
public void getBlogForeach(){
    SqlSession sqlSession = MybatisUtils.getSqlSession();
    BlogMapper blogMapper = sqlSession.getMapper(BlogMapper.class);

    Map<String, ArrayList<String>> map=new HashMap<>();
    ArrayList<String> list=new ArrayList<>();
    list.add("作者1");
    list.add("作者2");
    map.put("authors",list);
    blogMapper.getBlogForeach(map);
    sqlSession.close();

}
  1. 返回结果
image-20201222221022312

十一、Mybatis缓存

MyBatis 内置了一个强大的事务性查询缓存机制,它可以非常方便地配置和定制。

11.1 一级缓存

又名本地会话缓存

作用域:仅仅对一个会话中的数据进行缓存

使用方式:默认开启

作用效果:类似于map

使用测试

 @Test
    public void getBlogByIf(){
        SqlSession sqlSession = MybatisUtils.getSqlSession();
        BlogMapper blogMapper = sqlSession.getMapper(BlogMapper.class);
        Map<String,String> map=new HashMap<>();
//        map.put("title","%redis%");
        map.put("author","%1%");
        List<Blog> blogs=blogMapper.getBlogByIf(map);
        for (Blog blog : blogs) {
            System.out.println(blog);
        }
        System.out.println("-----------------------------");
        List<Blog> blogs2=blogMapper.getBlogByIf(map);
        for (Blog blog : blogs2) {
            System.out.println(blog);
        }
        sqlSession.close();

    }

返回结果(只查询一次数据库)

image-20201223202110666

11.2 二级缓存

又名全局缓存

作用范围:namespace名称空间

使用方式:默认开启

使用效果:

  • 映射语句文件中的所有 select 语句的结果将会被缓存。
  • 映射语句文件中的所有 insert、update 和 delete 语句会刷新缓存。
  • 缓存会使用最近最少使用算法(LRU, Least Recently Used)算法来清除不需要的缓存。
  • 缓存不会定时进行刷新(也就是说,没有刷新间隔)。
  • 缓存会保存列表或对象(无论查询方法返回哪种)的 1024 个引用。
  • 缓存会被视为读/写缓存,这意味着获取到的对象并不是共享的,可以安全地被调用者修改,而不干扰其他调用者或线程所做的潜在修改。

缓存清除策略:

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

开启缓存

    <settings>
<!--        全局性地开启或关闭所有映射器配置文件中已配置的任何缓存,默认值为true-->
        <setting name="cacheEnabled" value="true"/>
    </settings>

使用缓存

<mapper namespace="com.mybatis.mapper.BlogMapper">
    <cache eviction="FIFO" flushInterval="60000" size="512" readOnly="true"/>
    
    <insert id="insertBlog" parameterType="blog"></insert>
    <select id="getBlogByIf" parameterType="map" resultType="blog"></select>
</mapper>

提示: 二级缓存是事务性的。这意味着,当 SqlSession 完成并提交时,或是完成并回滚,但没有执行 flushCache=true 的 insert/delete/update 语句时,缓存会获得更新。

测试

  @Test
    public void getBlogByIf(){
        SqlSession sqlSession = MybatisUtils.getSqlSession();
        SqlSession sqlSession2 = MybatisUtils.getSqlSession();
        BlogMapper blogMapper = sqlSession.getMapper(BlogMapper.class);
        BlogMapper blogMapper2 = sqlSession2.getMapper(BlogMapper.class);
        Map<String,String> map=new HashMap<>();
        map.put("title","%redis%");
        map.put("author","%1%");
        List<Blog> blogs=blogMapper.getBlogByIf(map);
        System.out.println(blogs);
        System.out.println("-----------------------------");
        List<Blog> blogs2=blogMapper2.getBlogByIf(map);
        System.out.println(blogs2);
        System.out.println("------------------------------");
        System.out.println(blogs==blogs2);
        sqlSession.close();
        sqlSession2.close();
    }

数据库连接执行两次!

数据先保存在本地缓存中,只有当会话提交或关闭,才会提交到二级缓存中,因此blogMapper2不能从缓存中直接读取数据!

结果

image-20201223204835922

测试

    @Test
    public void getBlogByIf(){

        Map<String,String> map=new HashMap<>();
        map.put("title","%redis%");
        map.put("author","%1%");
        SqlSession sqlSession = MybatisUtils.getSqlSession();
        BlogMapper blogMapper = sqlSession.getMapper(BlogMapper.class);
        List<Blog> blogs=blogMapper.getBlogByIf(map);
        System.out.println(blogs);
        sqlSession.close();
        System.out.println("-----------------------------");
        SqlSession sqlSession2 = MybatisUtils.getSqlSession();
        BlogMapper blogMapper2 = sqlSession2.getMapper(BlogMapper.class);
        List<Blog> blogs2=blogMapper2.getBlogByIf(map);
        System.out.println(blogs2);
        sqlSession2.close();
        System.out.println("------------------------------");
        System.out.println(blogs==blogs2);
    }

数据库连接执行一次!

当sqlSession关闭后,数据会提交到全局缓存中,因此blogMapper2可以从全局缓存中直接读取数据!

结果

image-20201223205322075

执行顺序

用户查询---->二级缓存---->一级缓存---->查询数据库---->保存到一级缓存---->返回结果

11.3 自定义缓存EhCache

  • 是一个纯Java的进程内缓存框架,具有快速、精干等特点,是Hibernate中默认CacheProvider。

  • 是一种广泛使用的开源Java分布式缓存。主

  • 主要面向通用缓存,Java EE和轻量级容器。

t blogs2=blogMapper2.getBlogByIf(map);
System.out.println(blogs2);
System.out.println("------------------------------");
System.out.println(blogs==blogs2);
sqlSession.close();
sqlSession2.close();
}


**数据库连接执行两次!**

**数据先保存在本地缓存中,只有当会话提交或关闭,才会提交到二级缓存中,因此blogMapper2不能从缓存中直接读取数据!**

结果

<img src="C:\Users\zhoubao\AppData\Roaming\Typora\typora-user-images\image-20201223204835922.png" alt="image-20201223204835922" style="zoom:80%;" />

测试

```java
    @Test
    public void getBlogByIf(){

        Map<String,String> map=new HashMap<>();
        map.put("title","%redis%");
        map.put("author","%1%");
        SqlSession sqlSession = MybatisUtils.getSqlSession();
        BlogMapper blogMapper = sqlSession.getMapper(BlogMapper.class);
        List<Blog> blogs=blogMapper.getBlogByIf(map);
        System.out.println(blogs);
        sqlSession.close();
        System.out.println("-----------------------------");
        SqlSession sqlSession2 = MybatisUtils.getSqlSession();
        BlogMapper blogMapper2 = sqlSession2.getMapper(BlogMapper.class);
        List<Blog> blogs2=blogMapper2.getBlogByIf(map);
        System.out.println(blogs2);
        sqlSession2.close();
        System.out.println("------------------------------");
        System.out.println(blogs==blogs2);
    }

数据库连接执行一次!

当sqlSession关闭后,数据会提交到全局缓存中,因此blogMapper2可以从全局缓存中直接读取数据!

结果

image-20201223205322075

执行顺序

用户查询---->二级缓存---->一级缓存---->查询数据库---->保存到一级缓存---->返回结果

11.3 自定义缓存EhCache

  • 是一个纯Java的进程内缓存框架,具有快速、精干等特点,是Hibernate中默认CacheProvider。

  • 是一种广泛使用的开源Java分布式缓存。主

  • 主要面向通用缓存,Java EE和轻量级容器。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值