Mybatis

控制台打印SQL语句

// 修改application.yml文件
mybatis:
configuration:
log-impl: org.apache.ibatis.logging.stdout.StdOutImpl

 

指定mapper.xml文件路径

#  指定mapper.xml的文件路径
mybatis:
  mapper-locations: classpath:/mapper/*.xml

 

传递实体参数

不加@Param注解,取值的时候直接写属性

加了@Param注解,取值必须使用对象.属性的方式

 

动态SQL

trim标签

insert into t_car
        <trim prefix="(" suffix=")" suffixOverrides=",">
            <if test="vin != null">vin,</if>
            <if test="deviceId != null">device_id,</if>
            <if test="fenceId != null">fence_id,</if>
         </trim>
        <trim prefix="values (" suffix=")" suffixOverrides=",">
            <if test="vin != null">#{vin},</if>
            <if test="deviceId != null">#{deviceId},</if>
            <if test="fenceId != null">#{fenceId},</if>
         </trim>
</insert>

 

foreach标签

<foreach item="id" collection="array" open="(" separator="," close=")">
    #{id}
</foreach>

 

where标签

<where>  
    <if test="simNo != null  and simNo != ''"> and sim_no = #{simNo}</if>
    <if test="deptId != null "> and dept_id = #{deptId}</if>
    <if test="status != null "> and status = #{status}</if>
</where>

 

异常处理

MyBatis框架自定义了一个异常基类,叫做PersistenceException, 而PersistenceException是RuntimeException的子类

故Mybatis没有的异常都是非检查异常,直接使用全局异常处理器捕获即可

 

注释写法

使用 <!-- 注释 -->,千万别用 --(pgsql) 或者 #(mysql) 之类的

 

 

可能遇到的问题

mybatis版本号与SpringBoot不兼容

问题描述

SpringBoot 版本号为2.6.13

Mybatis 版本号为3.0.0

No qualifying bean of type 'com.example.dynamicdatasource.mapper.UserMapper' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)}

解决方案

降低Mybatis 的版本号

        <dependency>
            <groupId>org.mybatis.spring.boot</groupId>
            <artifactId>mybatis-spring-boot-starter</artifactId>
<!--            <version>3.0.0</version>-->
            <version>1.3.2</version>
        </dependency>

 

参考文章

【1】控制台打印SQL语句

【2】MyBatis的xml里的sql如何使用注释

posted @ 2024-01-12 15:38  先娶国王后取经  阅读(2)  评论(0编辑  收藏  举报