admin管理员组

文章数量:1446760

MyBatis框架操作数据库一>xml和动态Sql

Mybatis的开发有两种方式:注解和XML,这里我们讲解XML的方式和基于XML实现动态Sql

配置连接字符串和MyBatis:

这里要做两项: 1.数据库的连接配置 2.XML的配置 以上配置我们都是用yml的配置文件格式

数据库的连接配置:
代码语言:javascript代码运行次数:0运行复制
spring:
  application:
     name: Spring-mybaties
  datasource:
    url: jdbc:mysql://127.0.0.1:3306/mybatis_test?characterEncoding=utf8&useSSL=false&allowPublicKeyRetrieval=true
    username: root
    password: 123456
    driver-class-name: com.mysql.cj.jdbc.Driver

这里注意:自己连接数据库的密码,和数据库名

XML的配置:
代码语言:javascript代码运行次数:0运行复制
mybatis:
  configuration:
    log-impl: org.apache.ibatis.logging.stdout.StdOutImpl # 打印mybatis日志
    map-underscore-to-camel-case: true # 配置数据库和Java字段的驼峰转换
  mapper—locations: classpath:mapper/*.xml # XML配置

注意:xml文件配置要与resource/mapper目录下的xml文件对应

XML编写Sql:

model层:
代码语言:javascript代码运行次数:0运行复制
package com.suli.springmybaties.model;

import lombok.Data;

import java.util.Date;

@Data
public class UserInfo {
    private Integer id;
    private String username;
    private String password;
    private Integer age;
    private Integer gender;
    private String phone;
    private Integer deleteFlag;
    private Date createTime;
    private Date updateTime;
    
}

注意Java字段大驼峰数据库的字段蛇形命名,要记得加上驼峰转换配置,或者自己用标签来绑定


标签绑定代码:

代码语言:javascript代码运行次数:0运行复制
<resultMap id="BaseMap" type="com.suli.springmybaties.model.UserInfo">
    <id property="id" column="id"></id>
    <result property="deleteFlag" column="delete_flag"></result>
    <result property="createTime" column="create_time"></result>
    <result property="updateTime" column="update_time"></result>
</resultMap>

注意:

mapper层:

演示一个查询:

代码语言:javascript代码运行次数:0运行复制
package com.suli.springmybaties.mapper;

import com.suli.springmybaties.model.UserInfo;
import org.apache.ibatis.annotations.Mapper;

import java.util.List;

@Mapper
public interface UserInfoMapperXML {

    List<UserInfo> selectAll();

    List<UserInfo> selectAll2();
}

对应的XML文件:

代码语言:javascript代码运行次数:0运行复制
<!DOCTYPE mapper PUBLIC "-//mybatis//DTD Mapper 3.0//EN" ".dtd">
<mapper namespace="com.suli.springmybaties.mapper.UserInfoMapperXML">

<resultMap id="BaseMap" type="com.suli.springmybaties.model.UserInfo">
    <id property="id" column="id"></id>
    <result property="deleteFlag" column="delete_flag"></result>
    <result property="createTime" column="create_time"></result>
    <result property="updateTime" column="update_time"></result>
</resultMap>

    <select id="selectAll" resultType="com.suli.springmybaties.model.UserInfo">
        SELECT * from user_info
    </select>

    <select id="selectAll2" resultMap="BaseMap">
        SELECT * from user_info
    </select>

动态Sql:

动态SQL是Mybatis的强大特性之一,能够完成不同条件下不同的sql拼接


在特定的业务场景下可能,有的字段为非必须字段,不需要用户填,有的字段为必须字段,需要用户填写,这个时候我们的动态Sql就发挥作用,这个时候就可以使用 if标签

if 标签和trim标签:

trim标签需要搭配一些属性使用,如下: prefix:表示整个语句块,以prefix的值作为前缀 suffix:表示整个语句块,以suffix的值作为后缀 prefixOverrides:表示整个语句块要去除掉的前缀 suffixOverrides:表示整个语句块要去除掉的后缀


插入sql演示:INSERT INTO user_info (username, password,gender, age)values()

代码语言:javascript代码运行次数:0运行复制
<insert id="insertUser3">

        INSERT INTO user_info

    <trim prefix="(" suffix=")" suffixOverrides=",">
        <if test="username != null">
            username,
        </if>

        <if test="password != null">
            `password`,
        </if>

        <if test="gender != null">
            gender,
        </if>

        <if test="age != null">
            age
        </if>
    </trim>
    VALUES
    <trim prefix="(" suffix=")" suffixOverrides=",">
        <if test="username != null">
            #{username},
        </if>

        <if test="password != null">
           #{password},
        </if>

        <if test="gender != null">
            #{gender},
        </if>

        <if test="age != null">
            #{age}
        </if>

    </trim>

    </insert>
where标签:

当有业务需要写条件时一定需要where条件筛选: 比如:SELECT * FROM user_info WHERE phone = ? and delete_flag = ?


方法一:直接拼不使用where

代码语言:javascript代码运行次数:0运行复制
SELECT * FROM user_info WHERE
            <if test="phone != null">
                 phone = #{phone}
            </if>
            
            <if test="deleteFlag != null">
                and delete_flag = #{deleteFlag}
            </if>

方法二:也是拼接,这里不用去掉两个and

代码语言:javascript代码运行次数:0运行复制
SELECT * FROM user_info where 1= 1
            <if test="phone != null">
                and phone = #{phone}
            </if>

            <if test="deleteFlag != null">
                and delete_flag = #{deleteFlag}
            </if>

方法三:使用where标签:

代码语言:javascript代码运行次数:0运行复制
SELECT * FROM user_info 
        <where>
            <if test="phone != null">
                and phone = #{phone}
            </if>

            <if test="deleteFlag != null">
                and delete_flag = #{deleteFlag}
            </if>
        </where>


where标签总结: 1.当where标签内没有内容时,会自己去除where关键字 2.当where标签内有条件时,会添加where关键字,还会去除前面的“and”

Set标签:

当需要根据传入的用户对象属性来更新用户数据,可以使用set标签来指定动态内容


要实现:UPDATE user_info SET gender = ?, password = ?, age = ? WHERE id = ?

代码语言:javascript代码运行次数:0运行复制
<update id="updateByConfition">
        UPDATE user_info
            <set>
                <if test="gender != null">
                    gender = #{gender},
                </if>

                <if test="password != null">
                    password = #{password},
                </if>

                <if test="age != null">
                    age = #{age},
                </if>
            </set>
        WHERE id = #{id}

    </update>
Foreach标签:

有时会使用到 in关键来指定集合可以使用这个标签


** 例如:DELETE FROM user_info WHERE id in ( ? , ? )**

代码语言:javascript代码运行次数:0运行复制
 <delete id="batchDelete">

        DELETE FROM user_info WHERE id in
        <foreach collection="ids" open="(" close=")" separator="," item="id">
                #{id}
        </foreach>

    </delete>

当每个元素是一个对象,要插入多个:INSERT INTO user_info(username,password,age) VALUES (?,?,?) , (?,?,?)

代码语言:javascript代码运行次数:0运行复制
 <insert id="insertUser4">

        INSERT INTO user_info(username,`password`,age) VALUES
        <foreach collection="userInfos" item="userInfo" separator=",">
            (#{userInfo.username},#{userInfo.password},#{userInfo.age})
        </foreach>
    </insert>
本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。 原始发表:2025-03-15,如有侵权请联系 cloudcommunity@tencent 删除xml数据库sqlmybatis框架

本文标签: MyBatis框架操作数据库一>xml和动态Sql