首页 > 其他分享 >MyBatis

MyBatis

时间:2024-03-21 13:23:52浏览次数:12  
标签:xml bean Statement sql MyBatis new id

缓存

一级缓存

SqlSession级别,同一会话中多次重复的查询会使用以及缓存,默认开启

二级缓存

Mappr级别,需要在Mappr显性的开启,不同会话使用同样的Sql会查询二级缓存

Mapper.XML文件中常用标签

  • sql脚本相关
    select、insert、update、delete
  • 动态sql相关
    指定sql的基本数据类型:<resultMap>、 <parameterMap>、 <sql>、 <include>、 <selectKey>
    动态组件sql:trim|where|set|foreach|if|choose|when|otherwise|bind
    针对<sql>标签的脚本可以使用<include>标签引入

Dao的实现原理,方式是否可以重载

通过xml文件中的namspace与dao接口进行管理,xml中使用sql语句段的id与dao接口中的方法名进行绑定;当dao接口中的方法名重复,但是参数不一样时,可以重载使用,实例:

/**
 * Mapper接口里面方法重载
 */
public interface StuMapper {

 List<Student> getAllStu();

 List<Student> getAllStu(@Param("id") Integer id);
}

//xml文件
<select id="getAllStu" resultType="com.pojo.Student">
  select * from student
  <where>
    <if test="id != null">
      id = #{id}
    </if>
  </where>
</select>

Mybatis的插件(拦截器)使用

MyBatis 仅可以编写针对 ParameterHandler、 ResultSetHandler、 StatementHandler、 Executor 这 4 种接口的插件,MyBatis 使用 JDK 的动态代理,为需要拦截的接口生成代理对象以实现接口方法拦截功能,每当执行这 4 种接口对象的方法时,就会进入拦截方法,具体就是 InvocationHandler 的 invoke() 方法,当然,只会拦截那些你指定需要拦截的方法。
使用过程:

  1. 定义拦截器
@Intercepts({
        @Signature(type = ParameterHandler.class, method = "setParameters", args = PreparedStatement.class)
})
public class BaseDataInterceptor implements Interceptor {

    @Override
    public Object intercept(Invocation invocation) throws Throwable {
        return invokeSetParameter(invocation);
    }

    private Object invokeSetParameter(Invocation invocation) throws Exception {
        return null;
    }

    @Override
    public Object plugin(Object target) {
        return Interceptor.super.plugin(target);
    }

    @Override
    public void setProperties(Properties properties) {
        properties.put("connectionInitSqls", "set names 'utf8mb4'");
        Interceptor.super.setProperties(properties);
    }
}
  1. 在Mybatis配置文件中的sqlSession部分添加拦截器
@Bean(name = "sqlSessionFactory")
    public SqlSessionFactory sqlSessionFactory(DataSource dataSource) throws Exception {
        SqlSessionFactoryBean bean = new SqlSessionFactoryBean();
        bean.setDataSource(dataSource);
        bean.setMapperLocations(
                // 设置mybatis的xml所在位置,这里使用mybatis注解方式,没有配置xml文件
                new PathMatchingResourcePatternResolver().getResources("classpath*:com/zwj/learn/springcloud/**/dao/*.xml"));
        // 注册typehandler,供全局使用
        bean.setTypeHandlers(new UuidTypeHandler());

        BaseDataInterceptor sqlInterceptor = new BaseDataInterceptor();
        //创建属性值
        //将属性值设置到插件中
        Properties properties =  new Properties();
        sqlInterceptor.setProperties(new Properties());
        bean.setPlugins(sqlInterceptor);
        org.apache.ibatis.session.Configuration configuration = new org.apache.ibatis.session.Configuration();
        // 配置SQL打印日志
        configuration.setLogImpl(StdOutImpl.class);
        //开启驼峰映射配置
        configuration.setMapUnderscoreToCamelCase(true);
        bean.setConfiguration(configuration);
        return bean.getObject();
    }

<resultMap>与<resultType>的区别

resultMap需要自己提供映射配置,resultType会自动根据指定的数据类型做自动封装。

<resultMap>实现一对一和一对多映射

  • 一对一
<resultMap id="userResultMap" type="com.example.User">
  <id column="id" property="id" />
  <result column="username" property="username" />
  <result column="password" property="password" />
</resultMap>

<select id="selectUserById" resultMap="userResultMap" parameterType="int">
  SELECT * FROM user WHERE id = #{id}
</select>
  • 一对多
<resultMap id="userResultMap" type="com.example.User">
  <id column="id" property="id" />
  <result column="username" property="username" />
  <result column="password" property="password" />
  <collection property="orders" ofType="com.example.Order">
    <result column="order_id" property="id" />
    <result column="order_name" property="name" />
  </collection>
</resultMap>

<select id="selectUserWithOrdersById" resultMap="userResultMap" parameterType="int">
  SELECT u.*, o.*
  FROM user u
  LEFT JOIN order o ON u.id = o.user_id
  WHERE u.id = #{id}
</select>

批量插入

xml中使用foreach标签

<insert id="insertBatch" parameterType="list">  
    INSERT INTO your_table (column1, column2, ...)  
    VALUES   
    <foreach collection="list" item="item" index="index" separator=",">  
        (#{item.property1}, #{item.property2}, ...)  
    </foreach>  
</insert>

Mybatis执行器Executor

  • SimpleExecutor:
    每执行一次 update 或 select,就开启一个 Statement 对象,用完立刻关闭 Statement 对象。
  • ReuseExecutor:
    执行 update 或 select,以 sql 作为 key 查找 Statement 对象,存在就使用,不存在就创建,用完后,不关闭 Statement 对象,而是放置于 Map<String, Statement>内,供下一次使用。简言之,就是重复使用 Statement 对象。
  • BatchExecutor:
    执行 update(没有 select,JDBC 批处理不支持 select),将所有 sql 都添加到批处理中(addBatch()),等待统一执行(executeBatch()),它缓存了多个 Statement 对象,每个 Statement 对象都是 addBatch()完毕后,等待逐一执行 executeBatch()批处理。与 JDBC 批处理相同。
    使用方式:
    在Mybatis配置中的sqlSession部分添加执行器。

标签:xml,bean,Statement,sql,MyBatis,new,id
From: https://www.cnblogs.com/zly1015/p/18072646

相关文章

  • 一文搞懂idea中的根目录和路径(以Mybatis为例)
    1.根目录概念:1.1项目根目录(ProjectRoot)项目根目录是你在文件系统中为整个项目选择的顶层目录。它通常包含了项目的所有内容,包括源代码、构建配置文件、文档、测试文件等。在版本控制系统中(如Git),项目根目录通常是仓库的根目录。1.2内容根目录(ContentRoot)在IntelliJ......
  • Mybatis批量插入——踩坑点
    最近在进行批量插入,并且返回id的时候,遇到了几个比较抽象的点,首先,是mybatis版本不对,3.3.1之后才支持批量插入返回主键,所以在主键为null的时候,先检查mybatis版本。之后就是检查数据库中的id是否是自增的,如果不是,是否是雪花算法,当然雪花算法就不在本文中详述了。其次,在insert返回主......
  • SpringBoot整合Mybatis(SpringBoot3)
    依赖pom.xml:pom.xml<?xmlversion="1.0"encoding="UTF-8"?><projectxmlns="http://maven.apache.org/POM/4.0.0"xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xsi:schemaLocation="http://......
  • mybatis一二级缓存简介
    一、前言1,代码和准备工作见:mybatis工作原理简介-seeAll-博客园(cnblogs.com); 二、一级缓存1,效果展示1.1,测试代码代码中,使用SqlSession查询过一次数据;本例在此之后,继续添加一段代码,使用同样的SqlSession再次查询,观察结果数据来自于缓存还是数据库。 1.2,观察第一次......
  • Mybatis设置默认值
    在MyBatis中,可以通过在<resultMap>中使用<result>标签的column属性来设置默认值。但是,MyBatis本身不直接支持在<select>查询中设置默认值。如果需要为查询结果中的某个字段设置默认值,可以在结果映射中处理,或者在应用层面进行处理。以下是一个使用<resultMap>设置默认值的例......
  • SpringBoot整合Mybatis-Plus(SpringBoot3)
    依赖pom.xml:pom.xml<?xmlversion="1.0"encoding="UTF-8"?><projectxmlns="http://maven.apache.org/POM/4.0.0"xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xsi:schemaLocation="http://......
  • MyBatis3源码深度解析(十六)SqlSession的创建与执行(三)Mapper方法的调用过程
    文章目录前言5.9Mapper方法的调用过程5.10小结前言上一节【MyBatis3源码深度解析(十五)SqlSession的创建与执行(二)Mapper接口和XML配置文件的注册与获取】已经知道,调用SqlSession对象的getMapper(Class)方法,传入指定的Mapper接口对应的Class对象,即可获得一个动态......
  • 基于SSM框架的商城的设计与实现(JSP+java+springmvc+mysql+MyBatis)
    本项目包含程序+源码+数据库+LW+调试部署环境,文末可获取一份本项目的java源码和数据库参考。项目文件图 项目介绍随着电子商务的迅猛发展,网上购物已成为人们日常生活的一部分。基于SSM(Spring+SpringMVC+MyBatis)框架的商城系统因其轻量化、高效和易于维护等特点,成为......
  • 在线选课系统(JSP+java+springmvc+mysql+MyBatis)
    本项目包含程序+源码+数据库+LW+调试部署环境,文末可获取一份本项目的java源码和数据库参考。项目文件图 项目介绍在线选课系统作为现代教育体系中重要的信息化工具,它允许学生通过互联网进行课程选择,提高了教育管理的灵活性和效率。随着教学模式的多样化和个性化学习需求......
  • 基于携程旅行平台自由行的旅游线路管理信息系统(JSP+java+springmvc+mysql+MyBatis)
    本项目包含程序+源码+数据库+LW+调试部署环境,文末可获取一份本项目的java源码和数据库参考。项目文件图项目介绍随着个性化旅游需求的增加,自由行成为越来越多旅行者的选择。基于携程旅行平台的自由行旅游线路管理信息系统,旨在为用户提供更加灵活、个性化的旅游规划服务。系......