跳至主要內容

Mybatis

LiCheng大约 2 分钟

Mybatis

介绍🍊

  • 2022/5/10
  • 一个ORM数据操作框架,支持以xml形式动态sql编写

常用标签😃

  • select
  • update
  • delete
  • insert
  • if
  • where
  • sql
  • foreach

使用规范⛪

  • #{} 预编译sql语句在传值进去 不会sql注入
  • ${} 不编译sql语句直接传进去 引发sql注入

原理😎

spring环境🍇

  • 代码读取xml配置并且通过 new SqlSessionFactoryBuilder().build(inputStream); 进行Mybatis的构建
String resource = "org/mybatis/example/mybatis-config.xml";
InputStream inputStream = Resources.getResourceAsStream(resource);
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);

提示

代码

<?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>
  <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 resource="org/mybatis/example/BlogMapper.xml"/>
  </mappers>
</configuration>
 public SqlSessionFactory build(Reader reader, String environment, Properties properties) {
    try {
      XMLConfigBuilder parser = new XMLConfigBuilder(reader, environment, properties);
      return build(parser.parse());
    } catch (Exception e) {
      throw ExceptionFactory.wrapException("Error building SqlSession.", e);
    } finally {
      ErrorContext.instance().reset();
      try {
      	if (reader != null) {
      	  reader.close();
      	}
      } catch (IOException e) {
        // Intentionally ignore. Prefer previous error.
      }
    }
  }
  • 创建了XMLConfigBuilder对象,在返回调用build方法时传入(parser.parse()) 并解析

mybatis-plus🎈

LambdaQueryWrapper💢

  • 无需使用字符串形式去拼接属性
public User getUser(){
    try {
        String token = HttpServletUtil.getHeader("Token");
        String userId = TokenUtil.getUserId(token);
        LambdaQueryWrapper<User> lambda = new LambdaQueryWrapper<>();
        lambda.eq(User::getId, userId);
        return getOne(lambda);
    }catch (Exception e){
        throw new ServiceException("没有获取Token或Token中的用户不存在");
    }
}

配置插件🗾

package com.demo.config;

import com.baomidou.mybatisplus.annotation.DbType;
import com.baomidou.mybatisplus.autoconfigure.ConfigurationCustomizer;
import com.baomidou.mybatisplus.extension.MybatisMapWrapperFactory;
import com.baomidou.mybatisplus.extension.plugins.MybatisPlusInterceptor;
import com.baomidou.mybatisplus.extension.plugins.inner.OptimisticLockerInnerInterceptor;
import com.baomidou.mybatisplus.extension.plugins.inner.PaginationInnerInterceptor;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * @author lc
 * @date 2020/12/31
 */
@Configuration
public class MybatisPlusConfig {

    /**
     * 新的分页插件,一缓和二缓遵循mybatis的规则,需要设置 MybatisConfiguration#useDeprecatedExecutor = false 避免缓存出现问题(该属性会在旧插件移除后一同移除)
     */
    @Bean
    public MybatisPlusInterceptor mybatisPlusInterceptor() {
        MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();
        interceptor.addInnerInterceptor(new PaginationInnerInterceptor(DbType.MYSQL)); //分页配置
        interceptor.addInnerInterceptor(new OptimisticLockerInnerInterceptor()); //乐观锁配置
        return interceptor;
    }

    @Bean
    public ConfigurationCustomizer configurationCustomizer() {
        return configuration -> {
            configuration.setUseDeprecatedExecutor(false);//分页配置
            configuration.setObjectWrapperFactory(new MybatisMapWrapperFactory());//map转驼峰插件
        };
    }
}

MybatisX🎈

  • 代码生成插件

  • 第1步

  • 第2步