Mybatis动态SQL

文章详细介绍了Mybatis中的动态SQL标签,如where、if、choose、when、otherwise、set、trim和foreach的使用方法,以及如何在Springboot项目中整合Mybatis。示例展示了如何构建动态查询和更新语句,包括条件判断和批量操作。此外,还提到了Springboot整合Mybatis的基本步骤和配置要点。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Mybatis动态SQL的使用方式,和Springboot整合Mybatis的步骤

  1. where、if:条件判断标签,将判断的的语句写在test中

    where标签:

    • 会将第一个条件前面的逻辑运算符 (or ,and) 去掉,例如id满足条件,则会自动去掉id前面的ADN

    • 如果标签里面没有一个条件语句都不满足,则会不会生成where关键字

    if标签:

    • 在if标签里面的test中写入条件语句,如果符合语句则会自动生成标签内的SQL语句

    <select id="selectIf" parameterType="blog" resultMap="BaseResultMap" >
            select id, name, age from user
            <where>
                <if test="id != null and id != ''">
                    AND id = #{id}
                </if>
                <if test="name != null and name != ''">
                    AND name LIKE '%${name}%'
                </if>
                <if test="age != null and age != 0">
                    AND age = #{age}
                </if>
            </where>
        </select>

  2. choose、when、otherwise:类似Java中的switch语句,只有一个条件生效,也就是只执行满足的条件 when,没有满足的条件就执行 otherwise,表示默认条件。

    choose标签:

    • choose标签里面包含when,otherwise标签,只生成一个满足条件标签的SQL

    when标签:

    • 跟if标签类似,在标签内的test里面写条件判断,成立则生成对应的SQL

    otherwise标签:

    • 当when标签都不满足时,生成otherwise标签的SQL

    <select id="selectChoose" resultType="uyun.demo.User">
            select * from user
            <where>
                <choose>
                    <when test="name != null and name != ''">
                        AND name = #{name}
                    </when>
                    <when test="email != null and email != ''">
                        AND email = #{email}
                    </when>
                    <otherwise>
                        AND id = #{id}
                    </otherwise>
                </choose>
            </where>
        </select>
    ​
  3. set:使用set标签可以将动态的配置 SET 关键字,并剔除追加到条件末尾的任何不相关的逗号。

    <update id="updateSet" parameterType="uyun.demo.User">
            update user
            <set>
                <if test="name != null and name != ''">
                    name = #{name},
                </if>
                <if test="email != null and email != ''">
                    email = #{county},
                </if>
            </set>
            where id = #{id}
        </update>
  4. trim:是一个格式化标签,可以去掉自动生成的SQL前面的AND/OR

    四个参数

    • prefix:自动添加前缀

    • suffix:自动添加后缀

    • prefixOverrides:去掉第一个and或者是or

    • suffixOverrides:去掉最后一个逗号,也可以是其他的标记

    <select id="selectTrim" resultType="uyun.demo.User">
            select * from user
            <trim prefix="where" suffix="order by age" prefixOverrides="and | or" suffixOverrides=",">
                <if test="name != null and name != ''">
                    AND name = #{name}
                </if>
                <if test="email != null and email != ''">
                    AND email = #{email}
                </if>
            </trim>
        </select>
  5. foreach:类似Java中的循环,有下面几个参数

    • item:循环体中的具体对象。支持属性的点路径访问,如item.age,item.info.details,在list和数组中是其中的对象,在map中是value。

    • index:在list和数组中,index是元素的序号,在map中,index是元素的key,该参数可选。

    • open:表示该语句以什么开始

    • close:表示该语句以什么结束

    • separator:表示元素之间的分隔符

    • collection:参数类型

        <!--动态Sql: foreach标签, 批量插入-->
            <insert id="saveMany1" useGeneratedKeys="true" keyProperty="id">
            insert into user (user_id,user_name,user_email,password,user_age,user_sex)
            values
            <foreach collection="list" item="user" separator="," >
                (#{user.userId},#{user.userName},#{user.userEmail},#{user.password},#{user.userAge},#{user.userSex})
            </foreach>
        </insert>

    还有一种方式进行进行批量插入

    <insert id="saveMany2" useGeneratedKeys="true" keyProperty="id">
        <foreach collection="list" item="user" separator=";" >
            insert into user (user_id,user_name,user_email,password,user_age,user_sex)
            values
            (#{user.userId},#{user.userName},#{user.userEmail},#{user.password},#{user.userAge},#{user.userSex})
        </foreach>
    </insert>

    这两种的区别是:第一种是一条SQL语句执行很多插入语句,第二种是多条SQL执行多条插入语句。第二种更浪费性能,因为会有连接资源的浪费

    • 第一种的SQL语句是:insert into user (xx,xx,xx) values (v,v,v) ,(v,v,v)

    • 第二种的SQL语句是:insert into user (xx,xx,xx) values (v,v,v);insert into user (xx,xx,xx) values (v,v,v);insert into user (xx,xx,xx) values (v,v,v);

Springboot整合Mybatis

  1. 在pom文件中导入mybatis的启动项

    <!-- mybatis 与 spring boot 2.x的整合包 -->
            <dependency>
                <groupId>org.mybatis.spring.boot</groupId>
                <artifactId>mybatis-spring-boot-starter</artifactId>
                <version>1.3.2</version>
            </dependency>
  2. 在pom文件中补全其他依赖包(mysql,web启动项等)

    总的pom文件

    <?xml version="1.0" encoding="UTF-8"?>
    <project xmlns="http://maven.apache.org/POM/4.0.0"
             xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
             xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
        <modelVersion>4.0.0</modelVersion>
    
        <groupId>org.example</groupId>
        <artifactId>test</artifactId>
        <version>1.0-SNAPSHOT</version>
    
        <properties>
            <maven.compiler.source>8</maven.compiler.source>
            <maven.compiler.target>8</maven.compiler.target>
        </properties>
    
    
        <parent>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-parent</artifactId>
            <version>2.3.7.RELEASE</version>
            <relativePath/> <!-- lookup parent from repository -->
        </parent>
    
        <dependencies>
    
            <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-starter</artifactId>
            </dependency>
    
            <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-starter-web</artifactId>
            </dependency>
    
            <!-- mybatis 与 spring boot 2.x的整合包 -->
            <dependency>
                <groupId>org.mybatis.spring.boot</groupId>
                <artifactId>mybatis-spring-boot-starter</artifactId>
                <version>1.3.2</version>
            </dependency>
    
            <!--mysql JDBC驱动 -->
            <dependency>
                <groupId>mysql</groupId>
                <artifactId>mysql-connector-java</artifactId>
            </dependency>
    
            <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-starter-test</artifactId>
                <scope>test</scope>
            </dependency>
    
            <dependency>
                <groupId>org.projectlombok</groupId>
                <artifactId>lombok</artifactId>
                <optional>true</optional>
            </dependency>
        </dependencies>
    
    
        <build>
            <plugins>
                <plugin>
                    <groupId>org.springframework.boot</groupId>
                    <artifactId>spring-boot-maven-plugin</artifactId>
                </plugin>
            </plugins>
        </build>
    </project>
  3. 设置配置文件

    #端口号可以自己指定
    server.port=8082
    #数据库连接,还可以指定编码格式
    spring.datasource.url=jdbc:mysql://localhost:3306/demo?useUnicode=true&useSSL=false&serverTimezone=UTC
    spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
    spring.datasource.username=root
    spring.datasource.password=Admin@123
    #mybatis配置,这是个人实际工作中的配置习惯,有人喜欢在app的启动类上面添加mapperLocations的扫描包注解,
    #但是那样对新手容易忘记,下面的方式可以较好的实现与数据库表到实体类之间的驼峰转换
    mybatis.mapper-locations=classpath:mapper/*.xml
  4. 在mapper包下编写对应实体的mapper类

    注意:要在接口上面添加@Mapper注解(org.apache.ibatis.annotations.Mapper)

    @Mapper
    public interface UserMapper {
        /**
         * 新增用户
         * @param user
         */
        void save(User user);
        /**
         * 查询所有用户
         * @return
         */
        List<UserVO> queryAll();
        /**
         * 根据id删除
         * @param id
         * @return
         */
        int delete(String id);
        int update(User user);
    }
  5. 编写mapper对应的xml文件,完成增删改查

    注意:namespace一定要和上面的mapper接口对应起来

    <?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">
    ​
    <!--注意:一定要和UserMapper对应起来-->
    <mapper namespace="uyun.demo.mapper.UserMapper">
    ​
        <resultMap id="userMap" type="uyun.demo.pojo.User">
            <result column="user_id" property="userId"/>
            <result column="user_email" property="userEmail"/>
            <result column="user_name" property="userName"/>
            <result column="user_sex" property="userSex"/>
            <result column="user_age" property="userAge"/>
        </resultMap>
        <!--新增用户-->
        <insert id="save" parameterType="uyun.demo.pojo.User">
            insert into user (user_id,user_name,user_email,password,user_age,user_sex) values (#{userId},#{userName},#{userEmail},#{password},#{userAge},#{userSex})
        </insert>
        <!--查询所有的用户-->
        <select id="queryAll" resultMap="userMap">
            select * from user
        </select>
    </mapper>

常见问题:

  1. Invalid bound statement (not found):无效的绑定语句

    • 检查xxxmapper.xml文件的namespace是否正确

    • xxxMapper.java的方法在xxxMapper.xml中没有,然后执行Mapper的方法会报此

    • xxxMapper.java的方法返回值是List,而select元素没有正确配置ResultMap,或者只配置ResultType

    • 构建没有进去,请看一下target文件夹下面这些是否存在,没有请重新构建,maven处clean,再重新run试试

    • 检查target包里面的mapper文件夹路径是否和application.properties中配置的一样

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值