从零开始入门Mybatis

MyBatis3中文文档

一.MyBatis入门Demo

新建项目

  1. 新建一个默认maven项目
  2. 删除src目录
  3. 导入以下依赖
       <dependency>
           <groupId>org.mybatis</groupId>
           <artifactId>mybatis</artifactId>
           <version>3.5.2</version>
       </dependency>
       <dependency>
           <groupId>junit</groupId>
           <artifactId>junit</artifactId>
           <version>4.12</version>
       </dependency>
       <dependency>
           <groupId>mysql</groupId>
           <artifactId>mysql-connector-java</artifactId>
           <version>5.1.47</version>
       </dependency>
  1. 新建一个module
  2. 编写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=true&amp;characterEncoding=UTF-8"/>
                <property name="username" value="root"/>
                <property name="password" value="root"/>
            </dataSource>
        </environment>
    </environments>
    **<!-- 每一个Mapper.xml都需要在MyBatis核心配置文件中注册!!!-->**
    <mappers>
        <mapper resource="com/csdn/mapper/UserMapper.xml"/>
    </mappers>
</configuration>
  1. 编写工具类
  • MyBatisUtils
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 SqlSessionFactory sqlSessionFactory ;
    static{
        InputStream inputStream = null;
        try {
            String resource = "mybatis-config.xml";
            inputStream = Resources.getResourceAsStream(resource);
            sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    //有了 SqlSessionFactory,我们就可以从中获得 SqlSession 的实例了
    // SqlSession 完全包含了面向数据库执行 SQL 命令所需的所有方法
    // 你可以通过 SqlSession 实例来直接执行已映射的 SQL 语句
    public SqlSession getSession(){
        return  sqlSessionFactory.openSession();
    }
}

  1. 编写代码
  • User实体类
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 + '\'' +
                '}';
    }
}

  • UserMapper接口(Dao)
public interface UserMapper {
    //查询全部用户
    List<User> getUser();
}

  • UserMapper.xml接口实现(替换原来的DaoImpl)
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
        PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<!-- 关联对应的mapper接口 -->
<mapper namespace="com.csdn.mapper.UserMapper">
<!-- id为所关联接口的方法名  resultType为sql语句执行的返回值 -->
    <select id="getUser" resultType="com.csdn.pojo.User">
    select * from user
  </select>
</mapper>
  1. Junit单元测试

注意点:
org.apache.ibatis.binding.BindingException: Type interface com.csdn.mapper.UserMapper is not known to the MapperRegistry.
每一个Mapper.xml都需要在MyBatis核心配置文件中注册!!! 否则就会出现这个错误

重点:maven由于约定大于配置,可能遇到我们写的配置文件xml或者properties无法被导出或者生效

解决方案:在pom.xml中添加如下

<build>
        <resources>
            <resource>
                <directory>src/main/java/resources</directory>
                <includes>**/*.properties</includes>
                <includes>**/*.xml</includes>
                <filtering>true</filtering>
            </resource>
            <resource>
                <directory>src/main/java</directory>
                <includes>**/*.properties</includes>
                <includes>**/*.xml</includes>
                <filtering>true</filtering>
            </resource>
        </resources>
</build>
public class UserTest {
    @Test
    public void test(){
        //获取SqlSession对象
        SqlSession sqlSession = MyBatisUtils.getSession();
        //方式一:getMapper
        UserMapper mapper = sqlSession.getMapper(UserMapper.class);
        List<User> user = mapper.getUser();
        //方式二:已经过时,知道有这种方式就行了 看看就完事了
        //List<User> user = sqlSession.selectList("com.csdn.mapper.UserMapper.getUser");
        for (User user1 : user) {
            System.out.println(user1);
        }
        //关闭session
        sqlSession.close();
    }

}

可能会遇到的问题

  • 配置文件没有注册
  • 绑定接口错误
  • 方法名不对
  • 返回类型不对
  • maven资源导出错误

目录结构
在这里插入图片描述

二.CRUD

重点注意:增删改必须提交事务 否则直接白给!

  • 基于上面的类补充CRUD操作
    1. 编写接口方法
    2. 编写对应mapper.xml文件的sql语句
    3. Junit测试
  • UserMapper
public interface UserMapper {
    //获取全部用户
    List<User> getUser();
    //根据ID获取用户
    User getUserById(int id);
    //插入一个用户
    int addUser(User user);
    //修改一个用户
    int updateUser(User user);
    //删除一个用户
    int deleteUser(int id);
    //模糊查询
    List<User> getUserLike(String value);
}
  • 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">
<mapper namespace="com.csdn.mapper.UserMapper">
    <select id="getUser" resultType="com.csdn.pojo.User">
    select * from mybatis.user
  </select>

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

    <insert id="addUser" parameterType="com.csdn.pojo.User" >
        insert into mybatis.user (id, name, pwd) values (#{id},#{name},#{pwd});
    </insert>
    <update id="updateUser" parameterType="com.csdn.pojo.User">
        update mybatis.user set name=#{name},pwd=#{pwd} where id=#{id};
    </update>
    <delete id="deleteUser" parameterType="int">
        delete from mybatis.user where id=#{id}
    </delete>
        <select id="getUserLike" resultType="com.csdn.pojo.User">
        select * from mybatis.user where name like "%"#{value}"%"
    </select>
</mapper>
  • Junit测试
public class MapperTest {
    @Test
    public void getUser(){
        SqlSession sqlSession = MyBatisUtils.getSession();
        UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
        List<User> user = userMapper.getUser();
        for (User user1 : user) {
            System.out.println(user1);
        }
        sqlSession.close();
    }
    @Test
    public void getUserById(){
        SqlSession sqlSession=MyBatisUtils.getSession();
        UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
        User user = userMapper.getUserById(3);
        System.out.println(user);
        sqlSession.close();
    }
    @Test
    public void addUser(){
        SqlSession sqlSession=MyBatisUtils.getSession();
        UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
        userMapper.addUser(new User(6,"YJ","66666"));
        //增删改需要提交事务
        //提交事务
        sqlSession.commit();

        sqlSession.close();
    }
    @Test
    public void updateUser(){
        SqlSession sqlSession=MyBatisUtils.getSession();
        UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
        userMapper.updateUser(new User(6,"WYJ","123456"));
        sqlSession.commit();
        sqlSession.close();
    }
    @Test
    public void deleteUser(){
        SqlSession sqlSession=MyBatisUtils.getSession();
        UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
        userMapper.deleteUser(6);
        sqlSession.commit();
        sqlSession.close();
    }
    @Test
    public void getUserLike(){
        SqlSession sqlSession=MyBatisUtils.getSession();
        UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
        List<User> user = userMapper.getUserLike("李");
        for (User user1 : user) {
            System.out.println(user1);
        }
        sqlSession.close();
    }
}
模糊查询防止SQL注入
  • 在SQL语句中拼接通配符%

select * from mybatis.user where name like “%”#{value}"%"

  • 在java代码执行的时候传递通配符%

List user = userMapper.getUserLike("%李%");

入门内容End.

三.配置解析

1.核心配置文件
  • mybatis-config.xml
  • MyBatis 的配置文件包含了会深深影响 MyBatis 行为的设置和属性信息配置
2.环境配置(environments)
  • MyBatis 可以配置成适应多种环境
    不过要记住:尽管可以配置多个环境,但每个 SqlSessionFactory 实例只能选择一种环境.
    学会使用配置多套环境
  • MyBatis默认的事务管理器为JDBC. 连接池:POOLED
3.属性(properties)
  • 我们可以通过使用properties属性来实现引用配置文件
  • 这些属性都是可外部配置且可动态替换的,既可以在典型的 Java 属性文件中配置,亦可通过 properties 元素的子元素来传递
  • [db.properties]
driver=com.mysql.jdbc.Driver
url=jdbc:mysql://localhost:3306/mybatis?useSSL=true&useUnicode=true&characterEncoding=UTF-8
username=root
password=root
  • 在核心配置中引入外部配置文件
<properties resource="db.properties"/>
- 可以直接引入外部文件
- 可以在其中添加一些属性配置
- 如果两个文件有同一样的字段,优先使用外部配置的!
4.类型别名(typeAliases)
  • 类型别名是为 Java 类型设置一个短的名字
  • 用来减少类完全限定名的冗余
    <!--为实体类设置别名-->
    <typeAliases>
        <typeAlias type="com.csdn.pojo.User" alias="User"/>
    </typeAliases>
    <!-- 扫描指定包中所有的JavaBean类 不适用注解的情况下 默认别名为JavaBean的类名  *首字母小写* -->
    <typeAliases>
        <package name="com.csdn.pojo"/>
    </typeAliases>

** 两种情况根据JavaBean的数量来选择 **
扫描包也可以使用注解别名来实现DIY别名

@Alias("yj")
public class User {
}
5.设置(settings)

这是 MyBatis 中极为重要的调整设置,它们会改变 MyBatis 的运行时行为
(暂时只需要知道一下设置 多了我也记不住)

设置名描述有效值默认值
cacheEnabled(开启缓存)全局地开启或关闭配置文件中的所有映射器已经配置的任何缓存。True/FalseTrue
lazyLoadingEnabled(懒加载)延迟加载的全局开关。当开启时f,所有关联对象都会延迟加载。 特定关联关系中可通过设置 fetchType 属性来覆盖该项的开关状态。True/FalseFalse
mapUnderscoreToCamelCase(驼峰原则)是否开启自动驼峰命名规则(camel case)映射,即从经典数据库列名 A_COLUMN 到经典 Java 属性名 aColumn 的类似映射True/FalseFalse
logImpl (日志实现)指定 MyBatis 所用日志的具体实现,未指定时将自动查找。SLF4J / LOG4J / LOG4J2 / JDK_LOGGING / COMMONS_LOGGING / STDOUT_LOGGING / NO_LOGGING未设置
6.其他配置
  • typeHandlers(类型处理器)
  • objectFactory(对象工厂)
  • plugins插件
    • MyBatis Generator Core
    • MyBatis Plus
    • 通用mappe
7.映射器(mappers)

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

  • 方式一 [推荐使用]
    使用相对于类路径的资源引用
    <mappers>
        <mapper resource="com/csdn/mapper/UserMapper.xml"/>
    </mappers>
  • 方式二:
    使用class文件绑定注册
    • 注意点
      接口和它的Mapper配置文件必须同名!
      接口和它的Mapper配置文件必须在同一个包下!
    <mappers>
        <mapper class="com.csdn.mapper.UserMapper"/>
    </mappers>
  • 方式三:
    使用扫描包进行注入
    • 注意点
      接口和它的Mapper配置文件必须同名!
      接口和它的Mapper配置文件必须在同一个包下!
    <mappers>
       <package name="com.csdn.mapper"/>
    </mappers>
8.作用域(Scope)和生命周期

在这里插入图片描述
生命周期 和 作用域 是至关重要的,因为错误的使用会导致非常严重的并发问题

  • SqlSessionFactoryBuilder
    • 一旦创建了 SqlSessionFactory,就不再需要它了
    • 局部变量
  • SqlSessionFactory
    • 一旦被创建就在应用的运行期间一直存在,没有任何理由丢弃它或重新创建另一个实例
    • SqlSessionFactory 的最佳作用域是应用作用域
    • 最简单的就是使用单例模式或者静态单例模式
  • SqlSession
    • 不是线程安全的,因此是不能被共享的,所以它的最佳的作用域是请求或方法作用域
    • 用完之后就关闭连接,否则资源被占用!
      在这里插入图片描述

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

数据库中的字段:
在这里插入图片描述
Java代码

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

测试结果
在这里插入图片描述

   //select * from mybatis.user where id=#{id}
   //类型处理器(等同于下面)
  // select id,name,pwd from mybatis.user where id=#{id}

解决方案:

  • 起别名(低级方法)
    <select id="getUserById" resultType="User" parameterType="int">
        select id,name,pwd as password from mybatis.user where id=#{id}
    </select>

ResultMap
ResultMap 元素是 MyBatis 中最重要最强大的元素
ResultMap 的设计思想是,对于简单的语句根本不需要配置显式的结果映射,而对于复杂一点的语句只需要描述它们的关系就行了

  • ResultMap
    结果集映射
    id name pwd –> id name password
    <!-- 结果集映射-->
    <resultMap id="userMap" type="com.csdn.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">
        select * from mybatis.user where id=#{id}
    </select>

五.日志

日志工厂
如果一个数据库操作出现了异常.需要排错,日志就是最好的助手!
曾经: sout debug
如今:日志工厂
Mybatis 的内置日志工厂提供日志功能,内置日志工厂将日志交给以下其中一种工具作代理:

  • SLF4J

  • LOG4J (掌握)

  • LOG4J2

  • JDK_LOGGING

  • COMMONS_LOGGING

  • STDOUT_LOGGING (掌握)

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

  • STDOUT_LOGGING标准日志输出

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

在这里插入图片描述

  • Log4j
  • Log4J是什么?
    • Log4j是Apache的一个开源项目,通过使用Log4j,我们可以控制日志信息输送的目的地是控制台、文件、GUI组件
    • 可以控制每一条日志的输出格式
    • 通过定义每一条日志信息的级别,我们能够更加细致地控制日志的生成过程

如何使用?

  • 先导入log4j的包
<dependency>
    <groupId>log4j</groupId>
    <artifactId>log4j</artifactId>
    <version>1.2.17</version>
</dependency>
  • log4j.properties
### 配置根 ###
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 = logs/log.log
log4j.appender.file.MaxFileSize=10mb
log4j.appender.file.Threshold = DEBUG
log4j.appender.file.layout = org.apache.log4j.PatternLayout
log4j.appender.file.layout.ConversionPattern = %-d{yyyy-MM-dd HH:mm:ss}  [ %t:%r ] - [ %p ]  %m%n

### 设置输出sql的级别,其中logger后面的内容全部为jar包中所包含的包名 ###
log4j.logger.org.mybatis=DEBUG
log4j.logger.java.sql=DEBUG
log4j.logger.java.sql.Statement=DEBUG
log4j.logger.java.sql.PreparedStatement=DEBUG
log4j.logger.java.sql.ResultSet=DEBUG

  • 配置log4j为日志的实现
    <settings>
        <setting name="logImpl" value="LOG4J"/>
    </settings>

在这里插入图片描述
简单使用
1.在要使用log4j的类中,导入包org.apache.log4j.Logger
2.日志对象,参数为当前类的class

六.分页

思考:为什么要分页?-------------减少数据的处理量
使用Limit分页

  • 语法:SELECT * from user limit startIndex,pageSize;
    
  • SELECT * from user limit 3;  #[0,n]
    

使用MyBatis实现分页,核心SQL
1.接口

    //分页
    List<User4> getUserByLimit(Map<String,Integer> map);

2.Mapper.xml

    <select id="getUserByLimit" parameterType="map" resultMap="user4">
            select * from mybatis.user limit #{startIndex},#{pageSize}
    </select>

3.测试

    @Test
    public void limit(){
        SqlSession session = MyBatisUtils4.getSession();
        UserMapper4 mapper = session.getMapper(UserMapper4.class);
        HashMap<String, Integer> map = new HashMap<>();
        map.put("startIndex",1);
        map.put("pageSize",2);
        List<User4> user = mapper.getUserByLimit(map);
        for (User4 user4 : user) {
            System.out.println(user4);
        }
        session.close();

    }

七.使用注解开发

1.注解在接口上实现

public interface UserMapper5 {
    @Select("select * from user")
    List<User5> getUsers();
}

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

    <mappers>
        <mapper class="com.csdn.mapper.UserMapper5"/>
    </mappers>

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

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

  • a java library
  • plugs
  • build tools
  • with one annotation your class
    使用步骤
  1. 在IDEA中安装Lombok插件.
  • File--Settings--Plugins--搜索lombok---install---restart.
    
  1. 在项目中导入Lombok依赖
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <version>1.18.8</version>
        </dependency>
  1. 在实体类上加注解
@Data
public class User5 {
    private int id;
    private String name;
    private String pwd;
}

Tips:具体生成什么可以加注释并且IDEA左下角的Structure查看注解自动生成了哪些方法.

九.多对一处理

在这里插入图片描述

  • 多个学生,对应一个老师
  • 对于学生这边而言, 关联… 多个学生关联一个老师(多对一)
  • 对于老师而言, 集合… 一个老师有很多学生(一对多)

测试用SQL语句

create table `teacher`(
 `id` int(10) not null,
`name` varchar(30) DEFAULT null,
PRIMARY key (`id`)
)ENGINE=INNODB DEFAULT CHARSET=utf8

insert into teacher(`id`,`name`) values (1,'吴老师');

CREATE TABLE `student`(
 `id` int(10) not null,
 `name` varchar(30) DEFAULT null,
 `tid` int(10) DEFAULT null,
 PRIMARY key(`id`),
 key `fktid` (`tid`),
 CONSTRAINT `fktid` FOREIGN KEY (`tid`) REFERENCES `teacher` (`id`)
)ENGINE=INNODB DEFAULT CHARSET=utf8

insert into `student` (`id`,`name`,`tid`) values ('1','A','1');
insert into `student` (`id`,`name`,`tid`) values ('2','B','1');
insert into `student` (`id`,`name`,`tid`) values ('3','C','1');
insert into `student` (`id`,`name`,`tid`) values ('4','D','1');

测试环境搭建

  1. 导入依赖,核心配置文件,数据库配置文件
  2. 新建实体类Teacher Student
@Data
public class Student {
    private int id;
    private String name;
    private Teacher teacher;
}

@Data
public class Teacher {
    private int id;
    private String name;
}
  1. 编写Mapper接口
  2. 编写对应接口的Mapper.xml
  3. 在核心配置中注册绑定我们的Mapper接口或者文件!
  4. 测试

注意:复杂的属性我们需要单独处理,对象:association 集合:collection

  • 按照查询嵌套处理
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
        PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.csdn.mapper.StudentMapper">

    <select id="getStudent" resultMap="StuAndTea">
        SELECT * from student
    </select>
    <resultMap id="StuAndTea" 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" resultType="Teacher">
        select * from teacher where id=#{tid}
    </select>
</mapper>
  • 按照结果嵌套处理
    <select id="getStudent2" resultMap="StuAndTea2">
            select s.id sid,s.name sname,t.name tname from student s,teacher t where s.tid=t.id
    </select>
    <resultMap id="StuAndTea2" 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的多对一查询方式:

  • 子查询
  • 联表查询

十.一对多处理

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

  1. 环境搭建同上
    实体类
@Data
public class Teacher {
    private int id;
    private String name;
    private List<Student> students;
}

@Data
public class Student {
    private int id;
    private String name;
    private int tid;
}
  • 按照查询嵌套处理
        <select id="getTeacher" resultMap="StudentTeacher">
                select * from mybatis.teacher where id=#{tid}
        </select>
        <resultMap id="StudentTeacher" type="Teacher">
            <collection property="students" javaType="ArrayList" ofType="Student" select="getStudent" column="id"/>
        </resultMap>
        <select id="getStudent" resultType="Student">
            select * from mybatis.student where tid=#{tid}
        </select>
  • 按照结果嵌套处理
        <select id="getTeacher" resultMap="StudentTeacher">
                SELECT s.id sid,s.name sname,t.id tid,t.name tname
                FROM student s,teacher t
                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>
小结:
  • 对象-association
  • 集合-collection
  • javaType-用来指定实体类中属性的类型
  • ofType-用户指定映射到List或者集合中的POJO类型,泛型中的约束类型!

注意:

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

慢SQL 1s 1000s
面试高频

  • MySql引擎
  • InnoDB底层原理
  • 索引
  • 索引优化!

十一.动态SQL

动态SQL:动态SQL就是通过不同的条件生成不同的SQL语句(个人理解)

动态 SQL 元素和 JSTL 或基于类似 XML 的文本处理器相似。在 MyBatis 之前的版本中,有很多元素需要花时间了解。MyBatis 3 大大精简了元素种类,现在只需学习原来一半的元素便可。MyBatis 采用功能强大的基于 OGNL 的表达式来淘汰其它大部分元素。

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

搭建环境

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. 导包
  2. 编写配置文件
  3. 编写实体类
@Data
public class Blog {
    private int id;
    private String title;
    private String author;
    private Date createTime;
    private int views;

}
  1. 编写实体类对应Mapper接口和Mapper.xml文件

IF

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

trim (where, set)

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

choose (when, otherwise)

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

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

SQL片段

有些时候,我们可能会一些共用的部分抽取出来,方便复用!
1.使用sql标签抽取公共的部分

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

2.在需要使用的地方使用include标签

    <select id="queryBlogIf" parameterType="map" resultType="blog">
        select * from mybatis.blog
       <where>
          <include refid="if-title-author"></include>
       </where>
   </select>

3.注意事项

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

ForEach

  • select  * from  blog  where 1=1 and  (id=1 or id=2 or id=3)
    

在这里插入图片描述
在这里插入图片描述

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

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

  • 现在MyBatis中写出完整的Mysql语句,在对应的去修改成为我们的动态SQL

十二.缓存

简介:

  • 什么是缓存 [ Cache ]?
    • 存在内存中的临时变量.
    • 将用户经常查询的数据放在缓存中(内存)中,用户去查询就不用从磁盘上(关系型数据库数据文件)查询,从缓存中查询,从而提高查询效率,解决了高并发系统的性能问题.
  • 为什么使用缓存?
    • 减少和数据库的交互次数,减少系统开销,提高系统效率.
  • 什么样的数据能使用缓存?
    • 经常查询并且不经常改变的数据.

MyBatis缓存

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

一级缓存

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

测试步骤:
1.开启日志!
2.测试在一个Session中查询两次相同记录
3.查看日志输出
在这里插入图片描述
缓冲失效的情况:
1.查询不同的东西
2.查询不同的Mapper.xml
3.手动清理缓存 //session.clearCache();
4.增删改操作可能会改变原来的数据,所以必定会刷新缓存

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

    • 一级缓存就是一个ConcurrentHashMap (Debug可查看)

二级缓存

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

步骤:

  • 在核心配置文件中开启全局缓存
    <settings>
        <!--开启日志 -->
        <setting name="logImpl" value="STDOUT_LOGGING"/>
         <!--显式的开启缓存 增加代码可读性-->
        <setting name="cacheEnabled" value="true"/>
    </settings>
  • 在要使用二级缓存的Mapper.xml中开启
    <!--在当前Mapper.xml中开启二级缓存 -->
    <cache/>
  • 也可以自定义参数
<cache
  eviction="FIFO"
  flushInterval="60000"
  size="512"
  readOnly="true"/>
  • 测试
    • 问题:我们需要将实体类序列化,否则会报错.
    • org.apache.ibatis.cache.CacheException: Error serializing object.  Cause: java.io.NotSerializableException
      

小结

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

缓存原理
在这里插入图片描述

END

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
4S店客户管理小程序-毕业设计,基于微信小程序+SSM+MySql开发,源码+数据库+论文答辩+毕业论文+视频演示 社会的发展和科学技术的进步,互联网技术越来越受欢迎。手机也逐渐受到广大人民群众的喜爱,也逐渐进入了每个用户的使用。手机具有便利性,速度快,效率高,成本低等优点。 因此,构建符合自己要求的操作系统是非常有意义的。 本文从管理员、用户的功能要求出发,4S店客户管理系统中的功能模块主要是实现管理员服务端;首页、个人中心、用户管理、门店管理、车展管理、汽车品牌管理、新闻头条管理、预约试驾管理、我的收藏管理、系统管理,用户客户端:首页、车展、新闻头条、我的。门店客户端:首页、车展、新闻头条、我的经过认真细致的研究,精心准备和规划,最后测试成功,系统可以正常使用。分析功能调整与4S店客户管理系统实现的实际需求相结合,讨论了微信开发者技术与后台结合java语言和MySQL数据库开发4S店客户管理系统的使用。 关键字:4S店客户管理系统小程序 微信开发者 Java技术 MySQL数据库 软件的功能: 1、开发实现4S店客户管理系统的整个系统程序; 2、管理员服务端;首页、个人中心、用户管理、门店管理、车展管理、汽车品牌管理、新闻头条管理、预约试驾管理、我的收藏管理、系统管理等。 3、用户客户端:首页、车展、新闻头条、我的 4、门店客户端:首页、车展、新闻头条、我的等相应操作; 5、基础数据管理:实现系统基本信息的添加、修改及删除等操作,并且根据需求进行交流信息的查看及回复相应操作。
现代经济快节奏发展以及不断完善升级的信息化技术,让传统数据信息的管理升级为软件存储,归纳,集中处理数据信息的管理方式。本微信小程序医院挂号预约系统就是在这样的大环境下诞生,其可以帮助管理者在短时间内处理完毕庞大的数据信息,使用这种软件工具可以帮助管理人员提高事务处理效率,达到事半功倍的效果。此微信小程序医院挂号预约系统利用当下成熟完善的SSM框架,使用跨平台的可开发大型商业网站的Java语言,以及最受欢迎的RDBMS应用软件之一的MySQL数据库进行程序开发。微信小程序医院挂号预约系统有管理员,用户两个角色。管理员功能有个人中心,用户管理,医生信息管理,医院信息管理,科室信息管理,预约信息管理,预约取消管理,留言板,系统管理。微信小程序用户可以注册登录,查看医院信息,查看医生信息,查看公告资讯,在科室信息里面进行预约,也可以取消预约。微信小程序医院挂号预约系统的开发根据操作人员需要设计的界面简洁美观,在功能模块布局上跟同类型网站保持一致,程序在实现基本要求功能时,也为数据信息面临的安全问题提供了一些实用的解决方案。可以说该程序在帮助管理者高效率地处理工作事务的同时,也实现了数据信息的整体化,规范化与自动化。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值