狂神说MyBatis

狂神说MyBatis

在这里插入图片描述

在这里插入图片描述

1.简介

1.1 什么MyBatis?

在这里插入图片描述

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

mybatis–maven

<dependency>
    <groupId>org.mybatis</groupId>
    <artifactId>mybatis</artifactId>
    <version>3.4.6</version>
</dependency>

Github-Mybatis:https://github.com/mybatis/mybatis-3

中文文档:https://mybatis.org/mybatis-3/zh/index.html

1.2持久化

在这里插入图片描述

1.3持久层

在这里插入图片描述

1.4为什么需要mybatis?

在这里插入图片描述

在这里插入图片描述

2.第一个Mybatis程序

在这里插入图片描述

2.1搭建数据库

1.新建一个 普通maven项目

2.删除src当成父工程----------pom.xml 中 添加 packaging<>pom<>

3.导入依赖

需要在 dependencies标签中导入依赖

  • mysql驱动
<dependency>
    <groupId>mysql</groupId>
    <artifactId>mysql-connector-java</artifactId>
    <version>8.0.20</version>
</dependency>
  • mybatis 3.4.6
<dependency>
    <groupId>org.mybatis</groupId>
    <artifactId>mybatis</artifactId>
    <version>3.4.6</version>
</dependency>
  • junit单元测试4.12
<dependency>
    <groupId>junit</groupId>
    <artifactId>junit</artifactId>
    <version>4.12</version>
    <scope>test</scope>
</dependency>

2.2创建一个模块

2.2.1编写Mybatis工具类

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

import java.io.IOException;
import java.io.InputStream;

public class MybatisUtils {
    
    private static SqlSessionFactory sqlSessionFactory;

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

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

2.2.2编写mybatis的核心配置文件 mybatis-config

  • 位置:main/resources

  •   <?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.cj.jdbc.Driver"/>
                      <property name="url" value="jdbc:mysql://localhost:3306/codefuehng?useSSL=false&amp;useUnicode=true&amp;characterEncoding=UTF-8"/>
                      <property name="username" value="codefuehng"/>
                      <property name="password" value="3615yuhaijiao"/>
                  </dataSource>
              </environment>
          </environments>
          
      <!--每一个Mapper.xml都需要在mybatis核心文件中注册-->
          <mappers>
              <mapper resource="com/codefuehng/dao/UserMapper.xml"/>
          </mappers>
      </configuration>
    

2.3编写代码

  • 实体类

  • 实例类的属性名 一定要和数据库中的字段名相同-------------否则查询结果为null

  • 实体类还需要重写tostring方法、

  • 快捷键 alt+insert

    package com.codefuehng.pojo;
    
    /**
     * @author: codeyuaiaio
     * 实体类
     */
    public class User {
        private int userId;
        private String userName;
        private String userPwd;
        private String sex;
        private String email;
    
        public int getUserId() {
            return userId;
        }
    
        public void setUserId(int userId) {
            this.userId = userId;
        }
    
        public String getUserName() {
            return userName;
        }
    
        public void setUserName(String userName) {
            this.userName = userName;
        }
    
        public String getUserPwd() {
            return userPwd;
        }
    
        public void setUserPwd(String userPwd) {
            this.userPwd = userPwd;
        }
    
        public String getSex() {
            return sex;
        }
    
        public void setSex(String sex) {
            this.sex = sex;
        }
    
        public String getEmail() {
            return email;
        }
    
        public void setEmail(String email) {
            this.email = email;
        }
    
        public User(int userId, String userName, String userPwd, String sex, String email) {
            this.userId = userId;
            this.userName = userName;
            this.userPwd = userPwd;
            this.sex = sex;
            this.email = email;
        }
    
        public User() {
        }
    
        @Override
        public String toString() {
            return "User{" +
                    "userId=" + userId +
                    ", userName='" + userName + '\'' +
                    ", userPwd='" + userPwd + '\'' +
                    ", sex='" + sex + '\'' +
                    ", email='" + email + '\'' +
                    '}';
        }
    }
    
  • Mapper接口

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

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.codefuehng.mapper.UserMapper">
<!--select查询语句-->
    <select id="getUserList" resultType="com.codefuehng.pojo.User">
        select * from T_users
    </select>
</mapper>

2.4测试

注意一个容易出现的错误

org.apache.ibatis.binding.BindingException: Type interface com.codefuHeng.dao.UserMapper is not known to the MapperRegistry.

MapperRegistry是什么?

核心配置文件中注册mapper

<!--每一个Mapper.xml都需要在mybatis核心文件中注册-->
    <mappers>
        <mapper resource="com/codefuehng/mapper/UserMapper.xml"/>
    </mappers>
  • junit测试

  • 测试类最好写在try-finally(sqlSession.close(是一定要执行的)

    @Test
        public void test(){
            //第一步获得SqlSession对象
            SqlSession sqlSession = MybatisUtils.getSqlSession();
            try {
                //执行sql
                //方式一:getMapper
                UserMapper mapper = sqlSession.getMapper(UserMapper.class);
                List<User> userList = mapper.getUserList();
    
                //方式二:
    //        List<User> userList = sqlSession.selectList("com.codefuehng.dao.UserMapper.getUserList");
                for (User user : userList) {//快捷:先写集合名 点.for---->tab
                    System.out.println(user);
                }
            } finally {
                //关闭sqlSession
                sqlSession.close();
            }
    
        }
    

    可能遇到的问题

  • 配置文件没有注册

  •   <!--每一个Mapper.xml都需要在mybatis核心文件中注册-->
          <mappers>
              <mapper resource="com/codefuehng/dao/UserMapper.xml"/>
          </mappers>
    
  • 绑定接口错误

  • 方法名不对

  • 返回类型不对

  • Maven导出资源问题

  • java.lang.ExceptionInInitializerError

build

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

3.CRUD

1.namespace

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

2.select

查询语句:

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

    User getUserById(int Id);
    
  2. 编写对应的mapper实现类(mapper.xml)的sql语句

    <select id="getUserById" parameterType="int" resultType="com.codefuehng.pojo.User">
           select * from t_users where userId=#{id};
       </select>
    
  3. 测试

    @Test
        public void getUserById(){
            SqlSession sqlSession = MybatisUtils.getSqlSession();
            try {
                UserMapper mapper = sqlSession.getMapper(UserMapper.class);
                User userById = mapper.getUserById(4);
                System.out.println(userById);
                //提交事务
                sqlSession.commit();
            } finally {
                sqlSession.close();
            }
        }
    

3.Insert

<insert id="addUser" parameterType="com.codefuehng.pojo.User" >
    insert into t_users(userName,userPwd,sex,email) value(#{userName},#{userPwd},#{sex},#{email})
</insert>

4.update

<update id="updateUser" parameterType="com.codefuehng.pojo.User" >
    update t_users set userName=#{userName},userPwd=#{userPwd} where userId=#{userId}
</update>

5.delete

<delete id="deleteUser" parameterType="int">
    delete from t_users where userId=#{userId}
</delete>

注意点:增删改需要提交事务否则没反应 sqlSession.commit();

6.分析问题

  • 标签不要匹配错
  • resource绑定mapper,需要使用路径! 连接用 /
  • 程序配置文件必须符合规范!
  • 查错要从最后开始查
  • NullPointerException 没有注册到资源
  • 输出的XML文件中存在乱码问题
  • maven资源没有导出问题

7.万能Map

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

/**万能map*/
int updateUser2(Map<String,Object> map);
<!--map改-->
<update id="updateUser2" parameterType="map" >
    update t_users set userName=#{userName},userPwd=#{userPwd} where userId=#{userId}
</update>
@Test//改 map
public void updateUser2(){
    SqlSession sqlSession = MybatisUtils.getSqlSession();
    try {
        UserMapper mapper = sqlSession.getMapper(UserMapper.class);
        HashMap<String, Object> map = new HashMap<>();
        map.put("userName",2);
        map.put("userPwd",2);
        map.put("userId",2);
        int i = mapper.updateUser2(map);
        if(i>0){
            System.out.println("修改成功");
        }
        //提交事务
        sqlSession.commit();
    } finally {
        sqlSession.close();
    }
}

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

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

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

多个参数甩Map,或者注解

8.思考题

模糊查询怎么写?

  1. java代码执行的时候,传递通配符 % %

    List<User> userList = mapper.getUserList("%李%");
    
  2. 在sql拼接中使用通配符!(SQL注入问题)

    select * from t_users where userName like "%"#{value}"%"
    

4.配置解析

1.核心配置文件

  • mybatis-config.xml

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

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

2.环境配置(environment)

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

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

学会配置多种环境

Mybatis-config.xml中 environments标签中

在这里插入图片描述

Mybatis默认的事务管理器就是jdbc , 连接池:POOLED

3.属性(properties)

properties写在configuration标签中

在这里插入图片描述

在这里插入图片描述

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

这些属性都是可以外部配置的也可以动态替换的,既可以在典型的java属性文件中配置,也可以通过properties元素的子元素来传递。【db.properties】

顺序:

在这里插入图片描述

编写一个配置文件

db.properties

driver=com.mysql.cj.jdbc.Driver
url=jdbc:mysql://localhost:3306/codefuehng?useSSL=false&useUnicode=true;characterEncoding=UTF-8
username=codefuehng
password=3615yuhaijiao

在核心文件中引入

<!--引入外部配置文件-->
<properties resource="db.properties">
username=codefuehng
password=3615yuhaijiao
</properties>
  • 可以直接引入外部文件
  • 可以在其中增加一些属性配置
  • 如果两个文件有同一字段,优先使用外部文件的。

4.类型别名(typeAliases)

  • 类型别名是为java类型设置一个短的名字。

  • 存在的意义仅在于用来减少类完全限定名的冗余。

  • 方式一:

    <!--可以被实体类起别名-->
    <typeAliases>
        <typeAlias type="com.codefuehng.pojo.User" alias="User"/>
    </typeAliases>
    

也可以指定个包名,Mybatis会包名下面搜索需要的java Bean,比如:

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

  • 方式二:
<!--可以给实体类起别名  第二种-->
<typeAliases>
   <package name="com.codefuehng.pojo"/>
</typeAliases>

在实体类比较少的时候,使用第一种

如果实体类十分多的时候,建议使用第二种。

第一种可以DIY名,第二种不行。如果非要改,需要在实体类上加注解;

在这里插入图片描述

5.设置

在这里插入图片描述

在这里插入图片描述

6.其他配置

7.映射器(mapper)

MapperRegistry注册绑定我们的Mapper文件

方式一: .xml配置文件 连接用/

<!--每一个Mapper.xml都需要在mybatis核心文件中注册-->
<mappers>
    <mapper resource="com/codefuehng/dao/UserMapper.xml"/>
</mappers>

方式二:接口名 连接用.

<!--每一个Mapper.xml都需要在mybatis核心文件中注册-->
<mappers>
    <mapper class="com.codefuehng.dao.UserMapper"/>
</mappers>

方式三:直接连接包名 自动查询 标签用

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

注意点:

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

8.生命周期和作用域

在这里插入图片描述

生命周期和作用域,至关重要,因为错误的使用会导致非常严重的并发问题

sqlsessionFactorybuilder

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

sqlsessionFactory

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

SqlSession

  • 连接到连接池的一个请求
  • SqlSession的实例不是线程安全的,因此是不能被共享的,所以他的最佳的作用域是请求或方法作用域。
  • 用完之后需要赶紧关闭,否则资源被占用。
  • 在这里插入图片描述

这里面的每一个Mapper,就代表一个具体的业务

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

1.问题

数据库中的字段

在这里插入图片描述

新建一个项目,拷贝之前的,测试实体类字段不一致的情况

public class User {
    private Integer userId;
    private String userName;
    private String Pwd;//数据库中的是 userPwd
    private String sex;
    private String email;
}

测试出现问题

在这里插入图片描述

select * from t_users where userId=#{id};
//类型处理器
select userId,userName,userPwd... from t_users where userId=#{id};

解决方法

  • 起别名

    <select id="getUserById"  resultType="com.codefuehng.pojo.User">
        select userId,userName,Pwd as userPwd,... from t_users where userId=#{id};
    </select>
    

2.resultMap

userId   userName  userPwd
userId   userName  pwd
12
<!--    结果集映射-->
<resultMap id="userMap" type="User">
<!--    column数据库中的字段,property实体类中属性-->
    <result column="userPwd" property="pwd"></result>
</resultMap>

    <select id="getUserById"  resultMap="userMap">
        select * from t_users where userId=#{id};
    </select>
  • resultMap是mybatis中最重要最强大的元素
  • ResultMap 的设计思想是,对简单的语句做到零配置,对于复杂一点的语句,只需要描述语句之间的关系就行了
  • ResultMap最优秀的地方在于,如果你已经对它相当了解,但是根本就不需要现实的用到他们。

6.日志

6.1日志工厂

如果一个数据库操作,出现了异常,我们需要排错。日志就是最好的助手。

曾经:sout 。 debug

现在:日志工厂

在这里插入图片描述

在这里插入图片描述

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

STDOUT_LOGGING标准日志输出

在mybatis核心配置文件中,配置

<settings>
    <setting name="logImpl" value="STDOUT_LOGGING"/>
</settings>
  • STDOUT_LOGGING 日志查询结果

在这里插入图片描述

6.2什么是log4j ?

  • Log4j 是Apache的一个开源项目,通过实用Log4j,我们可以控制日志信息输送的目的地是控制台,文件,GUI组件。
  • 我们也可以控制每一条日志的输出格式;
  • 通过定义每一条日志信息的级别,我们能够更加细致的控制日志的生成过程。
  • 通过一个配置文件来灵活的进行配置,而不需要修改应用的代码。
  • log4j 日志设置(mybatis.config.xml)
<settings>
    <!--<setting name="logImpl" value="STDOUT_LOGGING"/>-->
    <setting name="logImpl" value="log4j"/>
</settings>
  • 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/codefuehng.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
123456789101112131415161718192021222324
<!--日志-->
<settings>
    <!--标准的日志工厂实现-->
    <!--<setting name="logImpl" value="STDOUT_LOGGING"/>-->
    <setting name="logImpl" value="LOG4J"/>
</settings>

log4j日志输出结果

在这里插入图片描述

错误排查

  • 有可能没有在pom中没有导入log4j依赖

简单实用

1.在要使用Log4j的类中,导入包 import org.apache.log4j.Logger;

2.日志对象,参数为当前类的class

static Logger logger = Logger.getLogger(UserDaoTest.class);

3.日志级别

logger.info("info:进入了testLog4j");
logger.info("debug:进入了testLog4j");
logger.info("error:进入了testLog4j");

7.分页

1.sql limit

为什么分页?

  • 减少数据的处理量

使用limit分页

select * from t_users limit 0,2;
select * from t_users Limit #{startIndex},#{pageSize};

使用Mybatis实现分页,核心sql

1.接口

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

2.Mapper.xml

<select id="getUserByLimit" parameterType="map" resultType="User">
    select * from t_users limit #{startIndex},#{pageSize}
</select>

3.测试

@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> userByLimit = mapper.getUserByLimit(map);
    for (User user : userByLimit) {
        System.out.println(user);
    }
    sqlSession.close();
}

2.RowBounds (java对象)

3.Mybatis pageHelper 分页插件

8.使用注解开发

8.1注解开发

在这里插入图片描述

本质:反射机制实现

底层:动态代理

在这里插入图片描述

8.2Mybatis详细执行流程

在这里插入图片描述

在这里插入图片描述

在这里插入图片描述

8.3 CRUD

MybatisUtil工具类中 autocommit(true) 自动提交事务

public static SqlSession getSqlSession() {
    return sqlSessionFactory.openSession(true);
}

UserMapper

编写接口,增加注解

//方法存在多个参数时,所有参数前面必须加上@param(“id”)注解

@Select("select * from t_users")
List<User> getUserAll();

//方法存在多个参数时,所有参数前面必须加上@param("id")注解
@Select("select * from t_users where userId=#{userId}")
User getUserById1(@Param("userId") int userId);

@Insert("insert into t_users(userId,userName,userPwd,sex,email) value(#{userId},#{userName},#{userPwd},#{sex},#{email})")
int addUser1(User user);

@Update("update t_users set userName=#{userName},userPwd=#{userPwd} where userId=#{userId}")
int updateUser1(User user);

@Delete("delete from t_users where userId=#{userId}")
int deleteUser1(int userId);

test

测试中只是不用提交事务了 sqlSession.cmmit();

@Test
public void getUserById1(){
    SqlSession sqlSession = MybatisUtils.getSqlSession();//不变

    UserMapper mapper = sqlSession.getMapper(UserMapper.class);
    User userById1 = mapper.getUserById1(4);
    System.out.println(userById1);

    sqlSession.close();//不变
}

注意:【我们必须要将接口注册到我们的核心配置文件中】

关于@Param()注解

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

9.Lombok

使用步骤:

  1. 在IDEA中安装Lombok插件

  2. 在项目中导入lombok的jar包

  3. 在这里插入图片描述

  4. 在实体类上 加注解即可

  5.  @Data
     @AllArgsConstructor
     @NoArgsConstructor
    
  6. 在这里插入图片描述

在这里插入图片描述

在这里插入图片描述

10.多对一

测试搭建环境

  1. 导入lombok
  2. 新建实体类Teacher,Student
  3. 建立Mapper接口
  4. 建立Mapper.XML文件
  5. 在核心配置文件中绑定注册我们的Mapper接口或者文件![方式很多,随心选]
  6. 测试查询是否能够成功

多对一 多个学生对应一个老师

按照查询嵌套处理

复杂的属性,我们需要单独处理

对象:association

集合:collection

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

按照结果嵌套处理

<!--按照结果嵌套处理-->
<select id="getStudent2" resultMap="StudentTeacher2">
    select s.id sid,s.name sname,t.name tname
    from student s,teacher t 
    where s.tid = t.id;
</select>

<resultMap id="StudentTeacher2" type="Student">
    <result property="id" column="sid"/>
    <result property="name" column="sname"/>
    <association property="teacher" javaType="Teacher">
        <result property="name" column="tname"/>
    </association>
</resultMap>

回顾Mysql多对一查询方式

  • 子查询
  • 联表查询

11.一对多

搭建环境 , 和刚才一样

实体类

student

public class Student {

    private int id;
    private String name;
    private int tid;

    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 int getTid() {
        return tid;
    }

    public void setTid(int tid) {
        this.tid = tid;
    }

    @Override
    public String toString() {
        return "Student{" +
                "id=" + id +
                ", name='" + name + '\'' +
                ", tid=" + tid +
                '}';
    }
}

teacher

public class Teacher {
    private int id;
    private String name;
    /**
     * 一个老师拥有多个学生
     */
    private List<Student> students;

    public List<Student> getStudents() {
        return students;
    }

    public void setStudents(List<Student> students) {
        this.students = students;
    }

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

    @Override
    public String toString() {
        return "Teacher{" +
                "id=" + id +
                ", name='" + name + '\'' +
                ", students=" + students +
                '}';
    }
}

TeacherMapper

按结果嵌套查询

<!--按结果嵌套查询-->
<select id="getTeacher" resultMap="StudentTeacher">
    select s.id sid,s.name sname,t.name tname,t.id tid
    from teacher t,student s
    where s.tid = t.id and t.id=1
</select>

<resultMap id="StudentTeacher" type="Teacher">
    <result property="id" column="tid"/>
    <result property="name" column="tname"/>
    <collection property="students" ofType="Student">
        <result property="id" column="sid"/>
        <result property="name" column="sname"/>
        <result property="tid" column="tid"/>
    </collection>
</resultMap>
12345678910111213141516

按照查询嵌套处理

<select id="getTeacher2" resultMap="StudentTeacher2">
    select * from teacher where id = #{tid}
</select>
<resultMap id="StudentTeacher2" type="Teacher">
    <!--javaType="ArrayList"  : 返回值类型
        ofType="Student  :  泛型类型
    -->
    <collection property="students" javaType="ArrayList" ofType="Student"
                select="getSudentByTeacherId" column="id"/>
</resultMap>
<select id="getSudentByTeacherId" resultType="Student">
    select * from student where tid = #{tid}
</select>
12345678910111213

注意点:

  • 保证sql的可读性,尽量保证通俗易懂
  • 注意一对多和多对一中,属性名和字段的问题
  • 如果问题不好排错,建议使用日志, 建议log4j

面试高频:

  • mysql引擎
  • innoDB底层原理
  • 索引
  • 索引优化!

12.动态sql

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

在这里插入图片描述

if

<select id="getUserAll" parameterType="map" resultType="User">
    select * from t_users where 1=1
    <if test="userName != null">
        and userName=#{userName}
    </if>
    <if test="userPwd != null">
        and userPwd =#{userPwd}
    </if>
</select>

choose(when otherwise)

相当于我们学的 switch ( case default)

<select id="getUserChoose" parameterType="map" resultType="User">
    select * from t_users
    <where>
        <choose>
            <when test="userName != null">
                and userName=#{userName}
            </when>
            <when test="sex != null">
                and sex=#{sex}
            </when>
            <otherwise>
                and userPwd=#{userPwd}
            </otherwise>
        </choose>
    </where>
</select>

trim(where set)

where(自动去除 and和or)

//UserMapper
List<User> getUserWhere(Map map);
12
<!--UserMapper.xml-->
<select id="getUserWhere" parameterType="map" resultType="User">
    select * from t_users
    <where>
        <if test="userName != null">
            or userName=#{userName}
        </if>
        <if test="userPwd != null">
            or userPwd =#{userPwd}
        </if>
    </where>

</select>

set(自动去除 ,逗号)----用于更新语句中

<update id="getUserSet" parameterType="map" >
    update t_users
    <set>
        <if test="userName != null">
            userName=#{userName},
        </if>
        <if test="userPwd != null">
            userPwd =#{userPwd},
        </if>
    </set>
    <where>
        userId=#{userId}
    </where>
</update>

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

Foreach

在这里插入图片描述

我们现在传一个万能的map, 这个map中可以存一个集合
注意: collection 和 item 的命名一定要和之后的 命名对应上 否则查找不到

select * from t_users where 1=1 and(userId=2 or userId=4 or userId=22)
1
<!--    select * from t_users where (userId=2 or userId=4 or userId=22)

        我们现在传一个万能的map, 这个map中可以存一个集合
        注意: collection   和  item  的命名一定要和之后的 命名对应上  否则查找不到
-->

<select id="getUserForEach" parameterType="map" resultType="User">
    select * from t_users
    <where>
        <foreach collection="userIds" item="userId"  open="("  close=")" separator="or">
            userId=#{userId}
        </foreach>
    </where>
</select>

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

    UserMapper mapper = sqlSession.getMapper(UserMapper.class);
    HashMap Map = new HashMap();
    ArrayList<Integer> userIds = new ArrayList<Integer>();
    userIds.add(2);
    userIds.add(4);
    userIds.add(22);

    Map.put("userIds",userIds);
    List<User> userForEach = mapper.getUserForEach(Map);
    for (User forEach : userForEach) {
        System.out.println(forEach);
    }
    sqlSession.close();
}

动态sql就是在拼接sql语句,只要我们保证sql的正确性,按照sql的格式,去排列组合就可以了

建议:

  • 现在Mysql中写出完整的sql , 再对应的去修改成为我们的动态sql实现通用即可!

13.sql片段

将一些重复的sql 提取出来 给一个id 然后调用id即可 方便复用

重复的主要是if判断

在这里插入图片描述

在这里插入图片描述

语法:

<sql id="自定义名字">
	//需要复用的sql
</sql>

在需要引用的地方添加
<include refid="自定义名字"></include>

注意:

  • 最要基于单表来定义sql片段
  • 不要存在where标签

14.缓存(了解)

简介

在这里插入图片描述

在这里插入图片描述

Mybatis缓存

在这里插入图片描述

一级缓存

在这里插入图片描述

测试步骤

  1. 开启日志
  2. 测试在一个session中查询两次相同的记录
  3. 查看日志输出

在这里插入图片描述

缓存失效的情况:

  1. 查询不同的东西
  2. 增删改操作,可能会改变原来数据,所以必定会刷新缓存.

在这里插入图片描述

  1. 查询不同的Mapper.xml
  2. 手动清理缓存

二级缓存

在这里插入图片描述

步骤:

  1. 开启全局缓存

在这里插入图片描述

  1. 在要使用二级缓存的mapper中开启

在这里插入图片描述

也可以自定义参数

在这里插入图片描述

  1. 测试
    1. 问题: 我们需要将实体类序列化! 否则就会报错!
    2. 在这里插入图片描述

小结:

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

缓存原理

在这里插入图片描述

缓存顺序

  1. 先看二级缓存中有没有
  2. 再看一级缓存中有没有
  3. 查询数据库

自定义缓存–ehcache(了解)

之后学Redis数据库来做缓存

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值