MyBatis学习笔记

MyBatis

简介

什么是 MyBatis?

  • MyBatis 是一款优秀的持久层框架
  • 它支持自定义 SQL、存储过程以及高级映射。
  • MyBatis 免除了几乎所有的 JDBC 代码以及设置参数和获取结果集的工作。
  • MyBatis 可以通过简单的 XML 或注解来配置和映射原始类型、接口和 Java POJO(Plain Old Java Objects,普通老式 Java 对象)为数据库中的记录。

如何获得MyBatis?

  • maven仓库
<!-- https://mvnrepository.com/artifact/org.mybatis/mybatis -->
<dependency>
    <groupId>org.mybatis</groupId>
    <artifactId>mybatis</artifactId>
    <version>3.4.6</version>
</dependency>
  • Github:https://github.com/mybatis/mybatis-3
  • 中文文档:https://mybatis.org/mybatis-3/zh/index.html

持久化

数据持久化

  • 持久化就是将程序的数据在持久状态和瞬间状态转化的过程
  • 内存:断电即失
  • 数据库(JDBC):io文件持久化

持久层

Dao层,Service层,Controller层…

  • 完成持久化工作的代码块
  • 层界限十分明显的的

MyBatis特点

  • 解除sql与程序代码的耦合:通过提供DAO层,将业务逻辑和数据访问逻辑分离。sql和代码的分离,提高了可维护性。
  • 提供映射标签,支持对象与数据库的orm字段关系映射
  • 提供对象关系映射标签,支持对象关系组建维护
  • 提供xml标签,支持编写动态sql。

第一个MyBatis程序

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,'倩倩','123456'),(3,'肖总','123456')

新建项目

  1. 新建一个普通的maven项目
  2. 删除src目录
  3. 导入maven依赖

pom.xml

    <!--导入依赖-->
    <dependencies>
        <!--MySQL驱动-->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.37</version>
        </dependency>
        <!--mybatis-->
        <!-- https://mvnrepository.com/artifact/org.mybatis/mybatis -->
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis</artifactId>
            <version>3.4.6</version>
        </dependency>
        <!--junit-->
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.11</version>
        </dependency>
    </dependencies>

2、创建一个模块

  1. 编写mybatis的核心配置文件

mybatis-config.xml

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration
        PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-config.dtd">
<!--configuration核心配置文件-->
<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=ture&amp;characterEncoding=UTF-8" />
                <property name="username" value="root"/>
                <property name="password" value="123456"/>
            </dataSource>
        </environment>
    </environments>
    <!--每一个Mapper.xml都需要在MyBatis核心配置文件中注册-->
    <mappers>
        <!--<mapper resource="org/mybatis/example/BlogMapper.xml"/>-->
        <mapper resource="com/sgl/dao/UserMapper.xml"/>
    </mappers>
</configuration>
  1. 编写mybatis工具类
package com.sgl.utils;

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;

//SqlSessionFactory -->  sqlSession
public class MybatisUtils {

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

    }
    
    //既然有了 SqlSessionFactory,顾名思义,我们可以从中获得 SqlSession 的实例
    //SqlSession 完全包含了面向数据库执行SQL命令所需的所有方法
    public static SqlSession getSqlSession(){
        //SqlSession sqlSession = sqlSessionFactory.openSession();
        //return sqlSession;
        return sqlSessionFactory.openSession();
    }

}

3、编写代码

  1. 实体类
package com.sgl.pojo;

//实体类
public class User {
    private int id;
    private String name;
    private String pwd;

    public User() {
    }

    public User(int id, String name, String pwd) {
        this.id = id;
        this.name = name;
        this.pwd = pwd;
    }

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getPwd() {
        return pwd;
    }

    public void setPwd(String pwd) {
        this.pwd = pwd;
    }

    @Override
    public String toString() {
        return "User{" +
                "id=" + id +
                ", name='" + name + '\'' +
                ", pwd='" + pwd + '\'' +
                '}';
    }
}
  1. Dao接口
package com.sgl.dao;

import com.sgl.pojo.User;
import java.util.List;

public interface UserDao {
    List<User> getUserList();
}
  1. 接口实现类 由原来的UserDaoImpl转换为Mapper配置文件

UserMapper.xml

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
        PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<!--namespace=绑定一个对应的Dao/Mapper接口-->
<mapper namespace="com.sgl.dao.UserDao">

    <!--select查询语句-->
    <select id="getUserList" resultType="com.sgl.pojo.User">
        select * from mybatis.user
    </select>
</mapper>

3、测试

MapperRegistry是什么?

核心配置文件注册mappers

  • junit测试
package com.sgl.dao;

import com.sgl.pojo.User;
import com.sgl.utils.MybatisUtils;
import org.apache.ibatis.session.SqlSession;
import org.junit.Test;

import java.util.List;

public class UserDaoTest {

    @Test
    public void test(){
        //第一步 获取SqlSession对象
        SqlSession sqlSession = MybatisUtils.getSqlSession();


        try {
            //方式一 getMapper
            UserDao userDao = sqlSession.getMapper(UserDao.class);
            List<User> userList = userDao.getUserList();

            //方式二 (不建议使用)
            //List<User> userList = sqlSession.selectList("com.sgl.dao.UserDao.getUserList");

            for (User user : userList) {
                System.out.println(user);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            //关闭sqlSession
            sqlSession.close();
        }
        
    }
}

结果:

在这里插入图片描述

CRUD

1、namespace

namespace中的包名要和Dao/mapper接口的包名一致

2、select

选择、查询语句:

  • id:对应的UserMapper接口中的方法名;
  • resultType:Sql语句执行的返回值
  • parameterType:参数类型
  1. 编写接口

UserMapper

package com.sgl.dao;

import com.sgl.pojo.User;
import java.util.List;

public interface UserMapper {
    //查询全部用户
    List<User> getUserList();

    //根据id查询用户
    User getUserById(int id);

    //insert一个用户
    int addUser(User user);

    //修改一个用户
    int updateUser(User user);

    //删除一个用户
    int deleteUser(int id);
}
  1. 编写对应的mapper语句

UserMapper.xml

<?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.sgl.dao.UserMapper">

    <!--select查询语句-->
    <select id="getUserList" resultType="com.sgl.pojo.User">
        select * from mybatis.user
    </select>
	<!--select查询语句-->
    <select id="getUserById" resultType="com.sgl.pojo.User" parameterType="int">
        select * from mybatis.user where id = #{id}
    </select>
	<!--insert插入语句-->
    <!--对象中的属性,可以直接取出来-->
    <insert id="addUser"  parameterType="com.sgl.pojo.User">
        insert into mybatis.user (id,name,pwd) values (#{id},#{name},#{pwd});
    </insert>
	<!--update更新语句-->
    <update id="updateUser" parameterType="com.sgl.pojo.User">
        update mybatis.user set name=#{name},pwd=#{pwd} where id=#{id} ;
    </update>
	<!--delete删除语句-->
    <delete id="deleteUser" parameterType="com.sgl.pojo.User" >
        delete from mybatis.user where id=#{id};
    </delete>

</mapper>
  1. 测试
package com.sgl.dao;

import com.sgl.pojo.User;
import com.sgl.utils.MybatisUtils;
import org.apache.ibatis.session.SqlSession;
import org.junit.Test;

import java.util.List;

public class UserDaoTest {

    //查询
    @Test
    public void test(){
        //第一步 获取SqlSession对象
        SqlSession sqlSession = MybatisUtils.getSqlSession();


        try {
            //方式一 getMapper
            UserMapper userDao = sqlSession.getMapper(UserMapper.class);
            List<User> userList = userDao.getUserList();

            //方式二 (不建议使用)
            //List<User> userList = sqlSession.selectList("com.sgl.dao.UserDao.getUserList");

            for (User user : userList) {
                System.out.println(user);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            //关闭sqlSession
            sqlSession.close();
        }

    }

    //查询
    @Test
    public void getUserById(){

        SqlSession sqlSession = MybatisUtils.getSqlSession();

        UserMapper mapper = sqlSession.getMapper(UserMapper.class);

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

        sqlSession.close();
    }

    //增删该需要提交事务
    //增
    @Test
    public void addUser(){

        SqlSession sqlSession = MybatisUtils.getSqlSession();

        UserMapper mapper = sqlSession.getMapper(UserMapper.class);

        int res = mapper.addUser(new User(5, "憨老表", "155555"));
        if (res>0){
            System.out.println("插入成功!");
        }

        //提交事务
        sqlSession.commit();
        sqlSession.close();
    }

    @Test
    //改
    public void updateUser(){

        SqlSession sqlSession = MybatisUtils.getSqlSession();

        UserMapper mapper = sqlSession.getMapper(UserMapper.class);

        mapper.updateUser(new User(5,"憨货","555555"));

        sqlSession.commit();
        sqlSession.close();
    }

    //删
    @Test
    public void deleteUser(){
        SqlSession sqlSession = MybatisUtils.getSqlSession();


        UserMapper mapper = sqlSession.getMapper(UserMapper.class);

        mapper.deleteUser(5);

        sqlSession.commit();
        sqlSession.close();
    }
}

增删改需要提交事务

3、insert

代码在上面

4、update

代码在上面

5、delete

代码在上面

6、Map(了解)

假设,我们的实体类,或者数据库中的表,字段过多,我们应当使用Map

    //Map
    int addUser2(Map<String,Object> map);
    <!--对象中的属性,可以直接取出来-->
    <insert id="addUser2"  parameterType="map">
        insert into mybatis.user (id,pwd) values (#{userId},#{userPwd});
    </insert>
    @Test
    public void addUser2(){

        SqlSession sqlSession = MybatisUtils.getSqlSession();

        UserMapper mapper = sqlSession.getMapper(UserMapper.class);

        Map<String, Object> map = new HashMap<>();

        map.put("userId",5);
        map.put("userPwd","666666");

        mapper.addUser2(map);

        sqlSession.commit();
        sqlSession.close();
    }

Map传递参数直接在sql中取出key即可 [parameterType=“map”]

对象传递参数,直接在sql中取对象的属性即可 [parameterType=“Object”]

只有一个基本类型参数的情况下,可以直接在sql中取到

多个参数用Map,或者注解

配置解析

1、核心配置文件

  • mybatis-config.xml
  • MyBatis 的配置文件包含了会深深影响 MyBatis 行为的设置和属性信息。 配置文档的顶层结构如下:
configuration(配置)   ********
properties(属性)       ********
settings(设置)       ********
typeAliases(类型别名)    ********
typeHandlers(类型处理器)
objectFactory(对象工厂)
plugins(插件)
environments(环境配置)     ********
environment(环境变量)      ********
transactionManager(事务管理器)    ********
dataSource(数据源)       ********
databaseIdProvider(数据库厂商标识)
mappers(映射器)       ********

2、环境配置(environments)

MyBatis 可以配置成适应多种环境

不过要记住:尽管可以配置多个环境,但每个 SqlSessionFactory 实例只能选择一种环境。

事务管理器(transactionManager)

在 MyBatis 中有两种类型的事务管理器(也就是 type=“[JDBC|MANAGED]”):

  • JDBC – 这个配置直接使用JDBC 的提交和回滚设施,它依赖从数据源获得的连接来管理事务作用域。
  • MANAGED – 这个配置几乎没做什么

数据源(dataSource)

dataSource 元素使用标准的 JDBC 数据源接口来配置 JDBC 连接对象的资源。

  • 大多数 MyBatis 应用程序会按示例中的例子来配置数据源。虽然数据源配置是可选的,但如果要启用延迟加载特性,就必须配置数据源。

有三种内建的数据源类型(也就是 type=“[UNPOOLED|POOLED|JNDI]”):

UNPOOLED POOLED JNDI

3、属性(properties)

可以通过properties属性来实现引用配置文件

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

db.properties

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

在核心配置文件(mybatis-config.xml)中引入

    <properties resource="db.properties">
        <property name="username" value="root"/>
        <property name="password" value="123456"/>
    </properties>
  • 可以直接引入外部配置文件
  • 可以在其中加入一些属性配置
  • 如果有两个文件有同一个字段,优先使用外部配置文件

4、类型别名(typeAliases)

  • 类型别名是为Java类型设置一个短的名字,用于减少类完全限定名的
    <!--可以给实体类起别名-->
    <typeAliases>
        <typeAlias type="com.sgl.pojo.User" alias="User"/>
    </typeAliases>
  • 也可以指定一个包名,MyBatis会在包名下面搜索需要的javaBean,比如:

扫描实体类的包,他的默认别名就为这个类的 类名首字母小写

    <!--可以给实体类起别名-->
    <typeAliases>
        <package name="com.sgl.pojo"/>
    </typeAliases>

实体类比较少,建议使用第一种方式(可以DIY(自定义)别名)

实体类较多,建议使用第二种方式(不可DIY(自定义)别名,如果非要改,需要在实体类上增加注解如下:

//实体类
@Alias("user")
public class User {}

5、设置(settings)

这是 MyBatis 中极为重要的调整设置,它们会改变 MyBatis 的运行时行为

设置名描述有效值默认值
cacheEnabled全局性地开启或关闭所有映射器配置文件中已配置的任何缓存。true | falsetrue
lazyLoadingEnabled延迟加载的全局开关。当开启时,所有关联对象都会延迟加载。 特定关联关系中可通过设置 fetchType 属性来覆盖该项的开关状态。true | falsefalse
logImpl指定 MyBatis 所用日志的具体实现,未指定时将自动查找。SLF4J 、LOG4J 、 LOG4J2 、 JDK_LOGGING 、 COMMONS_LOGGING 、 STDOUT_LOGGING 、 NO_LOGGING未设置

6、映射器(mapper)

MapperRegistry:注册绑定我们的Mapper文件

方式一:

<!-- 使用相对于类路径的资源引用 -->
<mappers>
  <mapper resource="com/sgl/dao/UserMapper.xml"/>
</mappers>

方式二:使用class文件绑定注册

<!-- 使用映射器接口实现类的完全限定类名 -->
<mappers>
		<mapper class="com.sgl.dao.UserMapper"/>-->

</mappers>

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

<!-- 将包内的映射器接口实现全部注册为映射器 -->
<mappers>
        <package name="com.sgl.dao"/>-->
</mappers>

方式二和方式三注意点:

  • 接口和他的Mapper配置文件必须同名
  • 接口和他的配置文件必须在同一个包下

7、其他配置

  • typeHandlers(类型处理器)
  • objectFactory(对象工厂)
  • plugins(插件)

作用域(Scope)和生命周期

SqlSessionFactoryBuilder

  • 一旦创建了 SqlSessionFactory,就不再需要它了
  • 局部变量

SqlSessionFactory

  • SqlSessionFactory 一旦被创建就应该在应用的运行期间一直存在,没有任何理由丢弃它或重新创建另一个实例
  • 因此 SqlSessionFactory 的最佳作用域是应用作用域
  • 最简单的就是使用单例模式或者静态单例模式

SqlSession

  • 连接到连接池的一个请求
  • 每个线程都应该有它自己的 SqlSession 实例。SqlSession 的实例不是线程安全的,因此是不能被共享的,所以它的最佳的作用域是请求或方法作用域
  • 用完之后需要关闭,否则资源被占用

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

数据库的字段和实体类的属性名

在这里插入图片描述

测试查询结果:

出现问题

在这里插入图片描述

解决方法:

  • 起别名
<select id="getUserById" resultType="com.sgl.pojo.User" parameterType="int">
    <!--select * from mybatis.user where id = #{id}-->
    select id,name,pwd as password from mybatis.user where id = #{id}
</select>
  • resultMap(结果映射)

resultMap(结果映射)

结果集映射

id   name   pwd
id   name   password
<!--结果集映射-->
<resultMap id="UserMap" type="com.sgl.pojo.User">
    <!--column数据库中的字段,property实体类中的属性-->
    <result column="id" property="id"/>
    <result column="name" property="name"/>
    <result column="pwd" property="password"/>
</resultMap>

<select id="getUserById" resultMap="UserMap" parameterType="int">
    select * from mybatis.user where id = #{id}
    <!--select id,name,pwd as password from mybatis.user where id = #{id}-->
</select>
  • resultMap 元素是 MyBatis 中最重要最强大的元素
  • ResultMap 的设计思想是,对简单的语句做到零配置,对于复杂一点的语句,只需要描述语句之间的关系就行了
  • ResultMap 的优秀之处——你完全可以不用显式地配置它们(就是相同的字段可以省略)
<!--结果集映射-->
<resultMap id="UserMap" type="com.sgl.pojo.User">
    <!--column数据库中的字段,property实体类中的属性-->
    <result column="pwd" property="password"/>
</resultMap>

解决后的结果:

在这里插入图片描述

日志

日志工厂

设置名描述有效值默认值
logImpl指定 MyBatis 所用日志的具体实现,未指定时将自动查找SLF4J 、LOG4J 、 LOG4J2 、 JDK_LOGGING 、 COMMONS_LOGGING 、 STDOUT_LOGGING 、 NO_LOGGING未设置
  • STDOUT_LOGGING 【掌握】

在mybatis核心配置文件中,配置我们的日志

<settings>
    <!--标准的日志工厂实现-->
    <setting name="logImpl" value="STDOUT_LOGGING"/>
</settings>

输出的结果:

在这里插入图片描述

LOG4J

什么是log4j?

  • Log4j是Apache的一个开源项目,通过使用Log4j,我们可以控制日志信息输送的目的地是控制台、文件、GUI组件
  • 我们也可以控制每一条日志的输出格式
  • 通过定义每一条日志信息的级别,我们能够更加细致地控制日志的生成过程
  • 这些可以通过一个配置文件来灵活地进行配置,而不需要修改应用的代码
  1. 先导入log4j包(maven仓库查找)
<!-- https://mvnrepository.com/artifact/log4j/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/sgl.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日志的实现(核心文件mybatis-config.xml中配置)
<settings>
    <setting name="logImpl" value="LOG4J"/>
</settings>

输出的结果: LOG4J与STDOUT_LOGGING输出结果基本一样

在这里插入图片描述

简单使用

  1. 在要使用Log4j的类中,导入包import org.apache.log4j.Logger;
  2. 日志对象,参数为当前类的class
static Logger logger = Logger.getLogger(UserDaoTest.class);
  1. 日记级别
logger.info("info:进入了testLog4j");
logger.debug("debug:进入了testLog4j");
logger.error("error:进入了testLog4j");

分页

Limit分页

MySQL使用Limit分页

语法:

SELECT * FROM user 	LIMIT startIndex,pageSize;
SELECT * FROM user LIMIT 3;  #[0,n]

使用Mybatis实现分页,核心SQL

  1. 接口UserMapper.java
//分页
List<User> getUserByLimit(Map<String,Integer> map);
  1. UserMapper.xml
<!--结果集映射-->
<resultMap id="UserMap" type="com.sgl.pojo.User">
    <!--column数据库中的字段,property实体类中的属性-->
    <!--<result column="id" property="id"/>-->
    <!--<result column="name" property="name"/>-->
    <result column="pwd" property="password"/>
</resultMap>

<select id="getUserByLimit" resultMap="UserMap" parameterType="map">
    select * from mybatis.user limit #{startIndex},#{pageSize}
</select>
  1. 测试UserDaoTest
@Test
public void getUserByLimit(){
    SqlSession sqlSession = MybatisUtils.getSqlSession();

    UserMapper mapper = sqlSession.getMapper(UserMapper.class);

    HashMap<String, Integer> map = new HashMap<>();
    map.put("startIndex",0);
    map.put("pageSize",2);

    List<User> userList = mapper.getUserByLimit(map);

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

    sqlSession.close();
}
  1. 测试结果
[org.apache.ibatis.logging.LogFactory]-Logging initialized using 'class org.apache.ibatis.logging.log4j.Log4jImpl' adapter.
[org.apache.ibatis.logging.LogFactory]-Logging initialized using 'class org.apache.ibatis.logging.log4j.Log4jImpl' adapter.
[org.apache.ibatis.datasource.pooled.PooledDataSource]-PooledDataSource forcefully closed/removed all connections.
[org.apache.ibatis.datasource.pooled.PooledDataSource]-PooledDataSource forcefully closed/removed all connections.
[org.apache.ibatis.datasource.pooled.PooledDataSource]-PooledDataSource forcefully closed/removed all connections.
[org.apache.ibatis.datasource.pooled.PooledDataSource]-PooledDataSource forcefully closed/removed all connections.
[org.apache.ibatis.transaction.jdbc.JdbcTransaction]-Opening JDBC Connection
[org.apache.ibatis.datasource.pooled.PooledDataSource]-Created connection 1337344609.
[org.apache.ibatis.transaction.jdbc.JdbcTransaction]-Setting autocommit to false on JDBC Connection [com.mysql.jdbc.JDBC4Connection@4fb64261]
[com.sgl.dao.UserMapper.getUserByLimit]-==>  Preparing: select * from mybatis.user limit ?,? 
[com.sgl.dao.UserMapper.getUserByLimit]-==> Parameters: 0(Integer), 2(Integer)
[com.sgl.dao.UserMapper.getUserByLimit]-<==      Total: 2
User{id=1, name='刚龙', password='123456'}
User{id=2, name='倩倩', password='123456'}
[org.apache.ibatis.transaction.jdbc.JdbcTransaction]-Resetting autocommit to true on JDBC Connection [com.mysql.jdbc.JDBC4Connection@4fb64261]
[org.apache.ibatis.transaction.jdbc.JdbcTransaction]-Closing JDBC Connection [com.mysql.jdbc.JDBC4Connection@4fb64261]
[org.apache.ibatis.datasource.pooled.PooledDataSource]-Returned connection 1337344609 to pool.

Process finished with exit code 0

RowBounds分页

  1. 接口UserMapper.java
//分页2
List<User> getUserByRowBounds();
  1. UserMapper.xml
<!--结果集映射-->
<resultMap id="UserMap" type="com.sgl.pojo.User">
    <!--column数据库中的字段,property实体类中的属性-->
    <!--<result column="id" property="id"/>-->
    <!--<result column="name" property="name"/>-->
    <result column="pwd" property="password"/>
</resultMap>

<!--分页2-->
<select id="getUserByRowBounds" resultMap="UserMap">
    select * from mybatis.user
</select>
  1. 测试UserDaoTest
@Test
public void getUserByRowBounds(){
    SqlSession sqlSession = MybatisUtils.getSqlSession();

    //RowBounds实现
    RowBounds rowBounds = new RowBounds(0, 2);

    //通过Java代码层面实现分页
    List<User> userList = sqlSession.selectList("com.sgl.dao.UserMapper.getUserByRowBounds",null,rowBounds);

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

    sqlSession.close();
}
  1. 测试结果
[org.apache.ibatis.logging.LogFactory]-Logging initialized using 'class org.apache.ibatis.logging.log4j.Log4jImpl' adapter.
[org.apache.ibatis.logging.LogFactory]-Logging initialized using 'class org.apache.ibatis.logging.log4j.Log4jImpl' adapter.
[org.apache.ibatis.datasource.pooled.PooledDataSource]-PooledDataSource forcefully closed/removed all connections.
[org.apache.ibatis.datasource.pooled.PooledDataSource]-PooledDataSource forcefully closed/removed all connections.
[org.apache.ibatis.datasource.pooled.PooledDataSource]-PooledDataSource forcefully closed/removed all connections.
[org.apache.ibatis.datasource.pooled.PooledDataSource]-PooledDataSource forcefully closed/removed all connections.
[org.apache.ibatis.transaction.jdbc.JdbcTransaction]-Opening JDBC Connection
[org.apache.ibatis.datasource.pooled.PooledDataSource]-Created connection 911312317.
[org.apache.ibatis.transaction.jdbc.JdbcTransaction]-Setting autocommit to false on JDBC Connection [com.mysql.jdbc.JDBC4Connection@365185bd]
[com.sgl.dao.UserMapper.getUserByRowBounds]-==>  Preparing: select * from mybatis.user 
[com.sgl.dao.UserMapper.getUserByRowBounds]-==> Parameters: 
User{id=1, name='刚龙', password='123456'}
User{id=2, name='倩倩', password='123456'}
[org.apache.ibatis.transaction.jdbc.JdbcTransaction]-Resetting autocommit to true on JDBC Connection [com.mysql.jdbc.JDBC4Connection@365185bd]
[org.apache.ibatis.transaction.jdbc.JdbcTransaction]-Closing JDBC Connection [com.mysql.jdbc.JDBC4Connection@365185bd]
[org.apache.ibatis.datasource.pooled.PooledDataSource]-Returned connection 911312317 to pool.

Process finished with exit code 0

分页插件(了解)

链接:https://pagehelper.github.io/

使用注解开发

注解增删改查(CRUD)

  1. 注解在接口上实现 UserMapper接口
@Select("select * from user")
List<User> getUsers();
  1. 核心配置文件中绑定接口 mybatis-config.xml
<!--绑定接口-->
<mappers>
    <mapper class="com.sgl.dao.UserMapper"/>
</mappers>
  1. 测试
import com.sgl.dao.UserMapper;
import com.sgl.pojo.User;
import com.sgl.utils.MybatisUtils;
import org.apache.ibatis.session.SqlSession;
import org.junit.Test;

import java.util.List;

public class UserMapperTest {

    @Test
    public void getUser(){
        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

  1. 在工具类(MybatisUtils)创建的时候实现自动提交事务
public static SqlSession getSqlSession(){
        return sqlSessionFactory.openSession(true);
    }
  1. 核心配置文件中绑定接口 mybatis-config.xml
<!--绑定接口-->
<mappers>
    <mapper class="com.sgl.dao.UserMapper"/>
</mappers>
  1. 编写接口 增加注解
package com.sgl.dao;


import com.sgl.pojo.User;
import org.apache.ibatis.annotations.*;

import java.util.List;

public interface UserMapper {

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

    //方法存在多个参数所有的参数前面必须加上@Param("id")注解
    //id =#{id} 对应 @Param("id")
    @Select("select * from user where id =#{id}")
    User getUserByID(@Param("id") int id);


    @Insert("insert into user(id,name,pwd) values(#{id},#{name},#{password})")
    int addUser(User user);

    @Update("update user set name=#{name},pwd=#{password} where id=#{id}")
    int updateUser(User user);

    @Delete("delete from user where id=#{uid}")
    int deleteUser(@Param("uid") int id);
}


  1. 测试类 UserMapperTest
import com.sgl.dao.UserMapper;
import com.sgl.pojo.User;
import com.sgl.utils.MybatisUtils;
import org.apache.ibatis.session.SqlSession;
import org.junit.Test;

import java.util.List;

public class UserMapperTest {

    @Test
    public void getUser(){
        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();
    }

    @Test
    public void getUserByID(){
        SqlSession sqlSession = MybatisUtils.getSqlSession();

        UserMapper mapper = sqlSession.getMapper(UserMapper.class);
        User user = mapper.getUserByID(1);
        System.out.println(user);

        sqlSession.close();
    }

    @Test
    public void addUser(){
        SqlSession sqlSession = MybatisUtils.getSqlSession();

        UserMapper mapper = sqlSession.getMapper(UserMapper.class);

        //不用在设置提交事务,在utils工具类中设置了sqlSessionFactory.openSession(true);
        mapper.addUser(new User(6,"周总","88888"));

        sqlSession.close();
    }

    @Test
    public void updateUser(){
        SqlSession sqlSession = MybatisUtils.getSqlSession();

        UserMapper mapper = sqlSession.getMapper(UserMapper.class);

        mapper.updateUser(new User(6,"狗哥","698574"));

        sqlSession.close();
    }

    @Test
    public void deleteUser(){
        SqlSession sqlSession = MybatisUtils.getSqlSession();

        UserMapper mapper = sqlSession.getMapper(UserMapper.class);

        mapper.deleteUser(6);

        sqlSession.close();
    }


}

@Param注解

  • 基本类型的参数或者String类型的参数,需要加上
  • 引用类型不需要加上
  • 如果只有一个基本类型,可加可不加(建议加上)
  • 在SQL中引用的就是@Param中设定的属性名

本质:反射机制实现 底层:动态代理(婚庆公司案例)

Mybatis执行流程

在这里插入图片描述

Lombok(了解)

ProjectLombok是一个java库,可以自动插入编辑器和构建工具,提高java的性能。永远不要再编写另一个getter或equals方法,使用一个注释,您的类就有了一个功能齐全的生成器,自动化了您的日志变量

使用步骤:

  1. 在IDEA中安装Lombok插件(有就不用安装)
  2. 在项目中导入Lombok的jar包
<!-- https://mvnrepository.com/artifact/org.projectlombok/lombok -->
<dependency>
    <groupId>org.projectlombok</groupId>
    <artifactId>lombok</artifactId>
    <version>1.18.20</version>
</dependency>
  1. 在实体类中加注解
@Getter and @Setter
@FieldNameConstants
@ToString
@EqualsAndHashCode
@AllArgsConstructor, @RequiredArgsConstructor and @NoArgsConstructor
@Log, @Log4j, @Log4j2, @Slf4j, @XSlf4j, @CommonsLog, @JBossLog, @Flogger, @CustomLog
@Data
@Builder
@SuperBuilder
@Singular
@Delegate
@Value
@Accessors
@Wither
@With
@SneakyThrows
@val
@var
experimental @var
@UtilityClass

@Data无参构造,get,set,toString,hashCode,equals,hashCode,canEqual

@AllArgsConstructor: 有参

@NoArgsConstructor: 无参

@EqualsAndHashCode : equals,hashCode,canEqual

效果:

在这里插入图片描述

多对一处理

多个学生对应一个老师

测试环境搭建(回顾之间知识)

SQL语句:

USE mybatis;
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


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. 导入Lombok-------->Lombok(了解)
  2. 新建实体类Teacher,Student
package com.sgl.pojo;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

@Data
@AllArgsConstructor
@NoArgsConstructor
public class Student {
    private int id;
    private String name;

    //学生需要关联一个老师
    private Teacher teacher;

}
package com.sgl.pojo;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

@Data
@AllArgsConstructor
@NoArgsConstructor
public class Teacher {
    private int id;
    private String name;
}
  1. 建立Mapper接口 StudentMapper TeacherMapper
package com.sgl.dao;

public interface StudentMapper {
}
package com.sgl.dao;

import com.sgl.pojo.Teacher;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Select;

public interface TeacherMapper {

    @Select("select * from teacher where id =#{tid}")
    Teacher getTeacher(@Param("tid") int id);
}
  1. 建立Mapper.xml文件 StudnetMapper.xml TeacherMapper.xml
<?xml version="1.0" encoding="UTF8" ?>
<!DOCTYPE mapper
        PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-mapper.dtd">

<mapper namespace="com.sgl.dao.StudentMapper">

</mapper>
<?xml version="1.0" encoding="UTF8" ?>
<!DOCTYPE mapper
        PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-mapper.dtd">

<mapper namespace="com.sgl.dao.TeacherMapper">

</mapper>
  1. 在核心配置文件(mybatis-config.xml)中绑定注册我们的Mapper接口或文件
    <mappers>
        <mapper class="com.sgl.dao.TeacherMapper"/>
        <mapper class="com.sgl.dao.StudentMapper"/>
    </mappers>
  1. 测试查询是否成功
import com.sgl.dao.TeacherMapper;
import com.sgl.pojo.Teacher;
import com.sgl.utils.MybatisUtils;
import org.apache.ibatis.session.SqlSession;

public class MyTest {

    public static void main(String[] args) {
        SqlSession sqlSession = MybatisUtils.getSqlSession();

        TeacherMapper mapper = sqlSession.getMapper(TeacherMapper.class);
        Teacher teacher = mapper.getTeacher(1);

        System.out.println(teacher);

        sqlSession.close();
    }
}

按照查询嵌套处理

StudentMapper 和 TeacherMapper 接口

package com.sgl.dao;

import com.sgl.pojo.Student;

import java.util.List;

public interface StudentMapper {

    //查询所有的学生信息,以及对应的老师的信息
    public List<Student> getStudent();

}
package com.sgl.dao;

import com.sgl.pojo.Teacher;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Select;

public interface TeacherMapper {

    @Select("select * from teacher where id =#{tid}")
    Teacher getTeacher(@Param("tid") int id);
}

StudentMapper.xml

<!--
    思路:
        1.查询所有的学生信息
        2.根据学生查询出来的tid,寻找对应的老师
    子查询
-->   
<select id="getStudent" resultMap="StudentTeacher">
    select * from student
</select>
<resultMap id="StudentTeacher" type="Student">
    <result property="id" column="id"/>
    <result property="name" column="name"/>
    <!--复杂的属性,需要单独处理,对象:association  集合:collection -->
    <association property="teacher" column="tid" javaType="Teacher" select="getTeacher"/>
</resultMap>
<select id="getTeacher" resultType="Teacher">
    select * from teacher where id = #{id}
</select>

按照结果嵌套处理

StudentMapper 和 TeacherMapper 接口

package com.sgl.dao;

import com.sgl.pojo.Student;

import java.util.List;

public interface StudentMapper {

    //查询所有的学生信息,以及对应的老师的信息
    public List<Student> getStudent2();

}
package com.sgl.dao;

import com.sgl.pojo.Teacher;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Select;

public interface TeacherMapper {

    @Select("select * from teacher where id =#{tid}")
    Teacher getTeacher(@Param("tid") int id);
}

StudentMapper.xml

<select id="getStudent2" resultMap="StudentTeacher2">
    select s.id sid,s.name sname,t.id tid,t.name tname
    from student s,teacher t
    where 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="name" column="tname"/>
        <result property="id" column="tid"/>
    </association>
</resultMap>

测试

import com.sgl.dao.StudentMapper;
import com.sgl.dao.TeacherMapper;
import com.sgl.pojo.Student;
import com.sgl.pojo.Teacher;
import com.sgl.utils.MybatisUtils;
import org.apache.ibatis.session.SqlSession;
import org.junit.Test;

import java.util.List;

public class MyTest {

    public static void main(String[] args) {
        SqlSession sqlSession = MybatisUtils.getSqlSession();

        TeacherMapper mapper = sqlSession.getMapper(TeacherMapper.class);
        Teacher teacher = mapper.getTeacher(1);

        System.out.println(teacher);

        sqlSession.close();
    }

    @Test
    public void getStudent(){

        SqlSession sqlSession = MybatisUtils.getSqlSession();

        StudentMapper mapper = sqlSession.getMapper(StudentMapper.class);

        List<Student> studentList = mapper.getStudent();

        for (Student student : studentList) {
            System.out.println(student);
        }

        sqlSession.close();
    }

    @Test
    public void getStudent2(){

        SqlSession sqlSession = MybatisUtils.getSqlSession();

        StudentMapper mapper = sqlSession.getMapper(StudentMapper.class);

        List<Student> studentList = mapper.getStudent2();

        for (Student student : studentList) {
            System.out.println(student);
        }

        sqlSession.close();
    }
}

按照查询嵌套处理:

Logging initialized using 'class org.apache.ibatis.logging.stdout.StdOutImpl' adapter.
PooledDataSource forcefully closed/removed all connections.
PooledDataSource forcefully closed/removed all connections.
PooledDataSource forcefully closed/removed all connections.
PooledDataSource forcefully closed/removed all connections.
Opening JDBC Connection
Created connection 1540270363.
==>  Preparing: select * from student 
==> Parameters: 
<==    Columns: id, name, tid
<==        Row: 1, 小明, 1
====>  Preparing: select * from teacher where id = ? 
====> Parameters: 1(Integer)
<====    Columns: id, name
<====        Row: 1, 秦老师
<====      Total: 1
<==        Row: 2, 小红, 1
<==        Row: 3, 小张, 1
<==        Row: 4, 小李, 1
<==        Row: 5, 小王, 1
<==      Total: 5
Student(id=1, name=小明, teacher=Teacher(id=1, name=秦老师))
Student(id=2, name=小红, teacher=Teacher(id=1, name=秦老师))
Student(id=3, name=小张, teacher=Teacher(id=1, name=秦老师))
Student(id=4, name=小李, teacher=Teacher(id=1, name=秦老师))
Student(id=5, name=小王, teacher=Teacher(id=1, name=秦老师))
Closing JDBC Connection [com.mysql.jdbc.JDBC4Connection@5bcea91b]
Returned connection 1540270363 to pool.

按照结果嵌套处理:

Logging initialized using 'class org.apache.ibatis.logging.stdout.StdOutImpl' adapter.
PooledDataSource forcefully closed/removed all connections.
PooledDataSource forcefully closed/removed all connections.
PooledDataSource forcefully closed/removed all connections.
PooledDataSource forcefully closed/removed all connections.
Opening JDBC Connection
Created connection 1540270363.
==>  Preparing: select s.id sid,s.name sname,t.id tid,t.name tname from student s,teacher t where s.tid=t.id 
==> Parameters: 
<==    Columns: sid, sname, tid, tname
<==        Row: 1, 小明, 1, 秦老师
<==        Row: 2, 小红, 1, 秦老师
<==        Row: 3, 小张, 1, 秦老师
<==        Row: 4, 小李, 1, 秦老师
<==        Row: 5, 小王, 1, 秦老师
<==      Total: 5
Student(id=1, name=小明, teacher=Teacher(id=1, name=秦老师))
Student(id=2, name=小红, teacher=Teacher(id=1, name=秦老师))
Student(id=3, name=小张, teacher=Teacher(id=1, name=秦老师))
Student(id=4, name=小李, teacher=Teacher(id=1, name=秦老师))
Student(id=5, name=小王, teacher=Teacher(id=1, name=秦老师))
Closing JDBC Connection [com.mysql.jdbc.JDBC4Connection@5bcea91b]
Returned connection 1540270363 to pool.

一对多处理

一个老师对应多个学生

测试环境搭建

  1. 导入Lombok-------->Lombok(了解)
  2. 新建实体类Teacher,Student
package com.sgl.pojo;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

@Data
@NoArgsConstructor
@AllArgsConstructor
public class Student {
    private int id;
    private String name;
    private int tid;


}
package com.sgl.pojo;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

import java.util.List;

@Data
@NoArgsConstructor
@AllArgsConstructor
public class Teacher {
    private int id;
    private String name;

    //一个老师对应多个学生
    private List<Student> students;


}

  1. 建立Mapper接口 StudentMapper TeacherMapper
package com.sgl.dao;

public interface StudentMapper {
}
package com.sgl.dao;

import com.sgl.pojo.Teacher;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Select;

import java.util.List;

public interface TeacherMapper {

    //获取所有老师
    List<Teacher> getTeacher();
}
  1. 建立Mapper.xml文件 StudnetMapper.xml TeacherMapper.xml
<?xml version="1.0" encoding="UTF8" ?>
<!DOCTYPE mapper
        PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-mapper.dtd">

<mapper namespace="com.sgl.dao.StudentMapper">

</mapper>
<?xml version="1.0" encoding="UTF8" ?>
<!DOCTYPE mapper
        PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-mapper.dtd">

<mapper namespace="com.sgl.dao.TeacherMapper">

    <select id="getTeacher" resultType="Teacher">
        select * from teacher
    </select>
</mapper>
  1. 在核心配置文件(mybatis-config.xml)中绑定注册我们的Mapper接口或文件
    <mappers>
        <mapper class="com.sgl.dao.TeacherMapper"/>
        <mapper class="com.sgl.dao.StudentMapper"/>
    </mappers>
  1. 测试查询是否成功
import com.sgl.dao.TeacherMapper;
import com.sgl.pojo.Teacher;
import com.sgl.utils.MybatisUtils;
import org.apache.ibatis.session.SqlSession;

import java.util.List;

public class MyTest {
    public static void main(String[] args) {

        SqlSession sqlSession = MybatisUtils.getSqlSession();

        TeacherMapper mapper = sqlSession.getMapper(TeacherMapper.class);
        List<Teacher> teacherList = mapper.getTeacher();

        for (Teacher teacher : teacherList) {
            System.out.println(teacher);
        }

        sqlSession.close();
    }
}

按照查询嵌套处理

TeacherMapper.xml

<!--按嵌查询嵌套-->
<select id="getTeacher2" resultMap="TeacherStudent2">
    select id,name from mybatis.teacher where id=#{tid}
</select>
<resultMap id="TeacherStudent2" type="Teacher">
    <result property="id" column="id"/>
    <result property="name" column="name"/>
    <collection property="students" javaType="ArrayList" ofType="Student" select="getStudent" column="id"/>
</resultMap>
<select id="getStudent" resultType="Student">
    select id,name,tid from mybatis.student where tid=#{tid}
</select>

按照结果嵌套处理

StudentMapper 和 TeacherMapper 接口

package com.sgl.dao;

public interface StudentMapper {

}
package com.sgl.dao;

import com.sgl.pojo.Teacher;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Select;

import java.util.List;

public interface TeacherMapper {

    //获取所有老师
    List<Teacher> getTeacher();

    //获取指定老师下的所有学生及老师的信息
    Teacher getTeacher1(@Param("tid") int id);
    Teacher getTeacher2(@Param("tid") int id);

}

TeacherMapper.xml

<!--按结果嵌套-->
<select id="getTeacher1" resultMap="TeacherStudent">
    select t.id tid,t.name tname,s.id sid,s.name sname
    from teacher t,student s
    where s.tid=t.id and t.id=#{tid}
</select>
<resultMap id="TeacherStudent" type="Teacher">
    <result property="id" column="tid"/>
    <result property="name" column="tname"/>
    <!--复杂的属性,需要单独处理,对象:association  集合:collection
            javaType="" 指定的属性类型
            集合中的泛型信息,需要使用ofType获取
        -->
    <collection property="students" ofType="Student">
        <result property="id" column="sid"/>
        <result property="name" column="tname"/>
        <result property="tid" column="tid"/>
    </collection>
</resultMap>

测试

import com.sgl.dao.TeacherMapper;
import com.sgl.pojo.Teacher;
import com.sgl.utils.MybatisUtils;
import org.apache.ibatis.session.SqlSession;
import org.junit.Test;

import java.util.List;

public class MyTest {
    public static void main(String[] args) {

        SqlSession sqlSession = MybatisUtils.getSqlSession();

        TeacherMapper mapper = sqlSession.getMapper(TeacherMapper.class);
        List<Teacher> teacherList = mapper.getTeacher();

        for (Teacher teacher : teacherList) {
            System.out.println(teacher);
        }

        sqlSession.close();
    }

    @Test
    public void getTeacher(){
        SqlSession sqlSession = MybatisUtils.getSqlSession();

        TeacherMapper mapper = sqlSession.getMapper(TeacherMapper.class);

        Teacher teacher = mapper.getTeacher1(1);
        System.out.println(teacher);

        sqlSession.close();
    }

    @Test
    public void getTeacher2(){
        SqlSession sqlSession = MybatisUtils.getSqlSession();

        TeacherMapper mapper = sqlSession.getMapper(TeacherMapper.class);

        Teacher teacher = mapper.getTeacher2(1);
        System.out.println(teacher);

        sqlSession.close();
    }
}

按照查询嵌套处理:

Logging initialized using 'class org.apache.ibatis.logging.stdout.StdOutImpl' adapter.
PooledDataSource forcefully closed/removed all connections.
PooledDataSource forcefully closed/removed all connections.
PooledDataSource forcefully closed/removed all connections.
PooledDataSource forcefully closed/removed all connections.
Opening JDBC Connection
Created connection 648525677.
==>  Preparing: select id,name from mybatis.teacher where id=? 
==> Parameters: 1(Integer)
<==    Columns: id, name
<==        Row: 1, 秦老师
====>  Preparing: select id,name,tid from mybatis.student where tid=? 
====> Parameters: 1(Integer)
<====    Columns: id, name, tid
<====        Row: 1, 小明, 1
<====        Row: 2, 小红, 1
<====        Row: 3, 小张, 1
<====        Row: 4, 小李, 1
<====        Row: 5, 小王, 1
<====      Total: 5
<==      Total: 1
Teacher(id=1, name=秦老师, students=[Student(id=1, name=小明, tid=1), Student(id=2, name=小红, tid=1), Student(id=3, name=小张, tid=1), Student(id=4, name=小李, tid=1), Student(id=5, name=小王, tid=1)])
Closing JDBC Connection [com.mysql.jdbc.JDBC4Connection@26a7b76d]
Returned connection 648525677 to pool.

按照结果嵌套处理:

Logging initialized using 'class org.apache.ibatis.logging.stdout.StdOutImpl' adapter.
PooledDataSource forcefully closed/removed all connections.
PooledDataSource forcefully closed/removed all connections.
PooledDataSource forcefully closed/removed all connections.
PooledDataSource forcefully closed/removed all connections.
Opening JDBC Connection
Created connection 648525677.
==>  Preparing: select t.id tid,t.name tname,s.id sid,s.name sname from teacher t,student s where s.tid=t.id and t.id=? 
==> Parameters: 1(Integer)
<==    Columns: tid, tname, sid, sname
<==        Row: 1, 秦老师, 1, 小明
<==        Row: 1, 秦老师, 2, 小红
<==        Row: 1, 秦老师, 3, 小张
<==        Row: 1, 秦老师, 4, 小李
<==        Row: 1, 秦老师, 5, 小王
<==      Total: 5
Teacher(id=1, name=秦老师, students=[Student(id=1, name=秦老师, tid=1), Student(id=2, name=秦老师, tid=1), Student(id=3, name=秦老师, tid=1), Student(id=4, name=秦老师, tid=1), Student(id=5, name=秦老师, tid=1)])
Closing JDBC Connection [com.mysql.jdbc.JDBC4Connection@26a7b76d]
Returned connection 648525677 to pool.

一对多,多对一小结和注意点

小结:

  1. 关联 association (多对一)
  2. 集合 collection (一对多)
  3. JavaType 和 ofType
    • JavaType用来指定实体类属性的类型
    • ofType用来指定映射到List或者集合中的pojo类型泛型中的约束类型

注意点:

  • 保证SQL的可读性,尽量保证通俗易懂
  • 注意一对多和多对一中属性和字段的问题
  • 问题不好排查,查看前方笔记,使用日志,建议使用Log4j

面试高频

MySQL引擎、INNODB底层原理、索引、索引优化(查文章看一下)

动态SQL

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

使用动态 SQL 并非一件易事,但借助可用于任何 SQL 映射语句中的强大的动态 SQL 语言,MyBatis 显著地提升了这一特性的易用性。

如果你之前用过 JSTL 或任何基于类 XML 语言的文本处理器,你对动态 SQL 元素可能会感觉似曾相识。在 MyBatis 之前的版本中,需要花时间了解大量的元素。借助功能强大的基于 OGNL 的表达式,MyBatis 3 替换了之前的大部分元素,大大精简了元素种类,现在要学习的元素种类比原来的一半还要少。

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

环境搭建

SQL语句:

CREATE TABLE `blog` (
	`id` VARCHAR(30) NOT NULL COMMENT '博客id',
	`title` VARCHAR(30) 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. 导包(偷懒用的)
<dependencies>
    <!-- https://mvnrepository.com/artifact/org.projectlombok/lombok -->
    <dependency>
        <groupId>org.projectlombok</groupId>
        <artifactId>lombok</artifactId>
        <version>1.18.20</version>
    </dependency>
</dependencies>
  1. 编写核心配置文件
<?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核心配置文件-->
<configuration>

    <!--引用外部配置文件-->
    <properties resource="db.properties"/>


    <settings>
        <!--标准的日志工厂实现-->
        <setting name="logImpl" value="STDOUT_LOGGING"/>
        <!--是否开启驼峰命名自动映射,即从经典数据库列名 A_COLUMN 映射到经典 Java 属性名 aColumn-->
        <setting name="mapUnderscoreToCamelCase" value="true"/>
    </settings>


    <!--可以给实体类起别名-->
    <typeAliases>
        <package name="com.sgl.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>

    <mappers>
        <mapper class="com.sgl.dao.BlogMapper"/>
    </mappers>
</configuration>
  1. 编写实体类
package com.sgl.pojo;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

import java.util.Date;

@Data
@NoArgsConstructor
@AllArgsConstructor
public class Blog {
    private String id;
    private String title;
    private String author;
    private Date createTime; //属性名和字段名不一致,在核心配置文件中配置
    private int views;
}
  1. 编写实体类对应的Mapper接口
package com.sgl.dao;

import com.sgl.pojo.Blog;

import java.util.List;
import java.util.Map;

public interface BlogMapper {

    //插入数据
    int addBook(Blog blog);
}
  1. 编写Mapper.xml文件
<?xml version="1.0" encoding="UTF8" ?>
<!DOCTYPE mapper
        PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-mapper.dtd">

<mapper namespace="com.sgl.dao.BlogMapper">

    <insert id="addBook" parameterType="Blog">
        insert into mybatis.blog (id,title,author,create_time,views)
        values(#{id},#{title},#{author},#{createTime},#{views})
    </insert>

</mapper>

测试并插入数据:

  1. 编写一个自动生成ID的工具类 IDutils.java
package com.sgl.utils;

import org.junit.Test;

import java.util.UUID;

@SuppressWarnings("all")  //抑制警告
public class IDutils {

    public static String getID(){
        return UUID.randomUUID().toString().replace("-","");
    }

    @Test
    public void test(){
        System.out.println(IDutils.getID());
    }
}
  1. 插入数据
import com.sgl.dao.BlogMapper;
import com.sgl.pojo.Blog;
import com.sgl.utils.IDutils;
import com.sgl.utils.MybatisUtils;
import org.apache.ibatis.session.SqlSession;
import org.junit.Test;

import java.util.Date;

public class MyTest {

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

        Blog blog = new Blog();
        blog.setAuthor("狂神说");
        blog.setCreateTime(new Date());
        blog.setViews(9999);


        blog.setId(IDutils.getID());
        blog.setTitle("Mybatis");
        mapper.addBook(blog);

        blog.setId(IDutils.getID());
        blog.setTitle("Java");
        mapper.addBook(blog);

        blog.setId(IDutils.getID());
        blog.setTitle("Spring");
        mapper.addBook(blog);

        blog.setId(IDutils.getID());
        blog.setTitle("微服务");
        mapper.addBook(blog);

        sqlSession.close();
    }
}

IF

BlogMapper接口

package com.sgl.dao;

import com.sgl.pojo.Blog;

import java.util.List;
import java.util.Map;

public interface BlogMapper {

    //插入数据
    int addBook(Blog blog);

    //查询博客
    List<Blog> queryBlogIf(Map map);
}

BlogMapper.xml

<?xml version="1.0" encoding="UTF8" ?>
<!DOCTYPE mapper
        PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-mapper.dtd">

<mapper namespace="com.sgl.dao.BlogMapper">

    <insert id="addBook" parameterType="Blog">
        insert into mybatis.blog (id,title,author,create_time,views)
        values(#{id},#{title},#{author},#{createTime},#{views})
    </insert>

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

测试:

@Test
public void queryBlogIf(){
    SqlSession sqlSession = MybatisUtils.getSqlSession();

    BlogMapper mapper = sqlSession.getMapper(BlogMapper.class);

    HashMap map = new HashMap();
    map.put("title","Java");
    map.put("author","狂神说");


    List<Blog> blogs = mapper.queryBlogIf(map);

    for (Blog blog : blogs) {
        System.out.println(blog);
    }

    sqlSession.close();
}

choose(when,otherwise)

<select id="queryBlogChoose" resultType="blog" parameterType="map">
    select * from mybatis.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>

trim(where,set)

<select id="queryBlogIf" parameterType="map" resultType="blog">
    select * from mybatis.blog 
    <where>
        <if test="title != null">
            title = #{title}
        </if>
        <if test="author != null">
            and author = #{author}
        </if>
    </where>
</select> 
<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和set的作用

在这里插入图片描述

在这里插入图片描述

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

SQL片段

有时候可能会将一些功能抽取出来,方便重复使用

  1. 使用SQL标签抽取公共的部分
<sql id="if-title-author">
    <if test="title != null">
        title = #{title}
    </if>
    <if test="author != null">
        and author = #{author}
    </if>
</sql>
  1. 在需要使用的地方使用include标签引用即可
<select id="queryBlogIf" parameterType="map" resultType="blog">
    select * from mybatis.blog
    <where>
        <include refid="if-title-author"/>
    </where>
</select>

注意事项:

  1. 最好基于单表来定义SQL片段
  2. SQL标签不要存在where标签,否则实现不了重复使用

Foreach

foreach(官方文档)

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

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

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

案例

SQL

插入代码重新运行以下插入数据,并修改了id为1,2,3,4,修改后要提交事务

在这里插入图片描述

BlogMapper接口

//查询第1,2,3,4号记录的博客
List<Blog> queryBlogForEach(Map map);

BlogMapper.xml

<select id="queryBlogForEach" parameterType="map" resultType="blog">
    select * from mybatis.blog
    <where>
        <foreach collection="ids"  item="id" open="and (" close=")" separator="or">
            id = #{id}
        </foreach>
    </where>
</select>

测试:

@Test
public void queryBlogForEach(){
    SqlSession sqlSession = MybatisUtils.getSqlSession();

    BlogMapper mapper = sqlSession.getMapper(BlogMapper.class);
    HashMap map = new HashMap();

    ArrayList<Integer> ids = new ArrayList<>();
    ids.add(1);
    ids.add(2);
    ids.add(3);
    ids.add(4);

    map.put("ids",ids);


    List<Blog> blogs = mapper.queryBlogForEach(map);
    for (Blog blog : blogs) {
        System.out.println(blog);
    }

    sqlSession.close();
}

结果:

在这里插入图片描述

动态SQL就是在拼接SQL语句,要保证SQL的正确性,按照SQL的格式

缓存

简介

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

作用:减少和数据库的交互次数,减少系统的开销,提高系统效率

Mybatis缓存

  • Mybatis包含一个非常强大的查询缓存特性,可以非常方便地定制和配置缓存,缓存可以极大地提升查询效率
  • Mybatis系统默认定义了两级缓存:一级缓存二级缓存
    • 默认情况下,只有一级缓存开启(SqlSession级别地缓存,也称本地缓存)
    • 二级缓存需要手动开启和配置,它是基于namespace级别地缓存
    • 为了提高扩展性,Mybatis定义了缓存接口Cache,我们可以通过实现Cache接口来自定义二级缓存

一级缓存

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

一级缓存是默认开启的,只在一次SqlSession中有效(连接到关闭之间的区间有效)

测试:

UserMapper接口

package com.sgl.dao;

import com.sgl.pojo.User;
import org.apache.ibatis.annotations.Param;

public interface UserMapper {
    //根据id查询用户
    User queryUserById(@Param("id") int id);

}

UserMapper.xml

<?xml version="1.0" encoding="UTF8" ?>
<!DOCTYPE mapper
        PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-mapper.dtd">


<mapper namespace="com.sgl.dao.UserMapper">
    <select id="queryUserById" resultType="user">
        select * from mybatis.user where id=#{id}
    </select>

</mapper>

测试:

import com.sgl.dao.UserMapper;
import com.sgl.pojo.User;
import com.sgl.utils.MybatisUtils;
import org.apache.ibatis.session.SqlSession;
import org.junit.Test;

public class MyTest {
    @Test
    public  void queryUserById(){
        SqlSession sqlSession = MybatisUtils.getSqlSession();

        UserMapper mapper = sqlSession.getMapper(UserMapper.class);

        User user = mapper.queryUserById(1);

        //手动清理缓存
        sqlSession.clearCache();

        System.out.println(user);
        System.out.println("=========================");

        User user2 = mapper.queryUserById(1);

        System.out.println(user2);

        System.out.println(user==user2);


        sqlSession.close();
    }

结果:

在这里插入图片描述

清理掉缓存之后的结果: sqlSession.clearCache();

在这里插入图片描述

缓存失效的情况

  1. 查询不同的东西
import com.sgl.dao.UserMapper;
import com.sgl.pojo.User;
import com.sgl.utils.MybatisUtils;
import org.apache.ibatis.session.SqlSession;
import org.junit.Test;

public class MyTest {
    @Test
    public  void queryUserById(){
        SqlSession sqlSession = MybatisUtils.getSqlSession();

        UserMapper mapper = sqlSession.getMapper(UserMapper.class);

        User user = mapper.queryUserById(1);

        System.out.println(user);
        System.out.println("=========================");

        User user2 = mapper.queryUserById(2);

        System.out.println(user2);

        System.out.println(user==user2);


        sqlSession.close();
    }
}

效果:

在这里插入图片描述

  1. 增删改操作,可能会改变原来的数据,所以必定会刷新

​ 在两次查询之间,插入修改语句

package com.sgl.dao;

import com.sgl.pojo.User;
import org.apache.ibatis.annotations.Param;

public interface UserMapper {
    //根据id查询用户
    User queryUserById(@Param("id") int id);

    int updateUser(User user);
}
import com.sgl.dao.UserMapper;
import com.sgl.pojo.User;
import com.sgl.utils.MybatisUtils;
import org.apache.ibatis.session.SqlSession;
import org.junit.Test;

public class MyTest {
    @Test
    public  void queryUserById(){
        SqlSession sqlSession = MybatisUtils.getSqlSession();

        UserMapper mapper = sqlSession.getMapper(UserMapper.class);

        User user = mapper.queryUserById(1);

        //修改用户
        //mapper.updateUser(new User(6,"李春龙","77777"));

        //手动清理缓存
        //sqlSession.clearCache();

        System.out.println(user);
        System.out.println("=========================");

        User user2 = mapper.queryUserById(2);

        System.out.println(user2);

        System.out.println(user==user2);


        sqlSession.close();
    }
}

效果:

在这里插入图片描述

  1. 查询不同的Mapper.xml文件
  2. 手动清理缓存
//手动清理缓存
sqlSession.clearCache();

二级缓存

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

步骤:

  1. 开启全局缓存
<settings>
    <!--显示的开启全局缓存-->
    <setting name="cacheEnabled" value="true"/>
</settings>
  1. 在要使用二级缓存的Mapper中开启

方式一:

<cache/>

方式二:

也可以自定义参数

<cache
       eviction="FIFO"
       flushInterval="60000"
       size="512"
       readOnly="true"/>
  1. 测试

UserMapper.xml 加入参数**useCache=“true”**使用缓存

<select id="queryUserById" resultType="user" useCache="true">
    select * from mybatis.user where id=#{id}
</select>

MyTest.java(两个SqlSession,所以最后为false)

import com.sgl.dao.UserMapper;
import com.sgl.pojo.User;
import com.sgl.utils.MybatisUtils;
import org.apache.ibatis.session.SqlSession;
import org.junit.Test;

public class MyTest {
    @Test
    public void queryUserById(){
        SqlSession sqlSession = MybatisUtils.getSqlSession();
        SqlSession sqlSession2 = MybatisUtils.getSqlSession();


        UserMapper mapper = sqlSession.getMapper(UserMapper.class);
        User user = mapper.queryUserById(1);
        System.out.println(user);
        sqlSession.close();


        UserMapper mapper2 = sqlSession2.getMapper(UserMapper.class);
        User user2 = mapper2.queryUserById(1);
        System.out.println(user2);

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

使用方式一开启缓存,测试MyTest.java会报错 ----> 解决:需要将实体类序列化

Caused by: java.io.NotSerializableException: com.sgl.pojo.User

继承Serializable接口

public class User implements Serializable {}

结果:

在这里插入图片描述

MyTest.java (一个SqlSession,所以为true)

import com.sgl.dao.UserMapper;
import com.sgl.pojo.User;
import com.sgl.utils.MybatisUtils;
import org.apache.ibatis.session.SqlSession;
import org.junit.Test;

public class MyTest {
    @Test
    public void queryUserById(){
        SqlSession sqlSession = MybatisUtils.getSqlSession();


        UserMapper mapper = sqlSession.getMapper(UserMapper.class);
        User user = mapper.queryUserById(1);
        System.out.println(user);

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

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

结果:

在这里插入图片描述

小结:

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

Mybatis缓存原理

在这里插入图片描述

自定义缓存-ehcache

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

  1. 在程序中使用ehcache,先导包
<!-- https://mvnrepository.com/artifact/org.mybatis.caches/mybatis-ehcache -->
<dependency>
    <groupId>org.mybatis.caches</groupId>
    <artifactId>mybatis-ehcache</artifactId>
    <version>1.2.1</version>
</dependency>
  1. 在mapper中指定使用我们的ehcache缓存实现
<!--自定义缓存-->
<cache type="org.mybatis.caches.ehcache.EhcacheCache"/>
  1. ehcache.xml(在resource资源目录下
<?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 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"/>
</ehcache>

完结

  • 2
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

等慢慢

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值