Mybatis XML配置文件实现增删改查的示例代码

 更新时间:2025年03月25日 08:31:56   作者:鸽鸽程序猿  
本文主要介绍了Mybatis XML配置文件实现增删改查的示例代码,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧

一、环境准备

在使用XML来实现的数据库操作的时候,我们的依赖下载与前面的使用注解时的依赖是一样的。

		<dependency>
            <groupId>org.mybatis.spring.boot</groupId>
            <artifactId>mybatis-spring-boot-starter</artifactId>
            <version>3.0.4</version>
        </dependency>

        <dependency>
            <groupId>com.mysql</groupId>
            <artifactId>mysql-connector-j</artifactId>
            <scope>runtime</scope>
        </dependency>
        
		<dependency>
            <groupId>org.mybatis.spring.boot</groupId>
            <artifactId>mybatis-spring-boot-starter-test</artifactId>
            <version>3.0.4</version>
            <scope>test</scope>
        </dependency>

在配置文件yml格式,也需要添加上跟使用注解时的配置。还要多加上mybatis. mapper-locations: classpath:mapper/**Mapper.xml

# 数据库连接配置 
spring:
  application:
    name: spring-mybatis-demo

  datasource:
    url: jdbc:mysql://127.0.0.1:3306/mybatis_test?characterEncoding=utf8&useSSL=false
    username: root
    password: 1234
    driver-class-name: com.mysql.cj.jdbc.Driver

mybatis:
  configuration: # 配置打印 MyBatis⽇志
    log-impl: org.apache.ibatis.logging.stdout.StdOutImpl
    map-underscore-to-camel-case: true #配置驼峰⾃动转换

# 配置 mybatis xml 的⽂件路径,在 resources/mapper 创建所有表的 xml ⽂件 
  mapper-locations: classpath:mapper/**Mapper.xml

二、简单启动

我们先安装一个插件MybatisX,可以帮我们更简单实现xml文件与接口之间的跳转。

mapper接口:

package com.example.springmybatisdemo.mapper;

import com.example.springmybatisdemo.model.UserInfo;
import org.apache.ibatis.annotations.Mapper;

import java.util.List;
@Mapper
public interface UserMapperXML {
    List<UserInfo> selectAll();
}

xml文件:

<?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">
<mapper namespace="com.example.springmybatisdemo.mapper.UserMapperXML">

    <select id="selectAll" resultType="com.example.springmybatisdemo.model.UserInfo">
        select * from user_info;
    </select>

</mapper>

  • <mapper> 标签:需要指定 namespace 属性,表⽰命名空间,值为 UserMapperXML 接⼝的全限定名,包括全包名.类名。
  • <select> 查询标签:是⽤来执⾏数据库的查询操作的:
  • id :是和 Interface (接⼝)中定义的⽅法名称⼀样的,表⽰对接⼝的具体实现⽅法。
  • resultType :是返回的数据类型,也就是我们定义的实体类.

测试:

package com.example.springmybatisdemo.mapper;

import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;

import static org.junit.jupiter.api.Assertions.*;
@SpringBootTest
class UserMapperXMLTest {
    @Autowired
    private UserMapperXML userMapperXML;
    @BeforeEach
    void setUp() {
    }

    @AfterEach
    void tearDown() {
    }

    @Test
    void selectAll() {
        System.out.println(userMapperXML.selectAll());
    }
}

结果:

三、增< insert id = >

使用标签< Insert >来写入数据,直接使⽤UserInfo对象的属性名来获取参数。

    <insert id="insertOne">
        insert into user_info (username, password, age) values (#{username},#{password},#{age})
    </insert>

测试函数:

    @Test
    void insertOne() {
        UserInfo userInfo = new UserInfo();
        userInfo.setAge(8);
        userInfo.setPassword("888");
        userInfo.setUsername("888");
        Integer result = userMapperXML.insertOne(userInfo);
        System.out.println("增加函数:"+ result);
    }

测试结果:

四、返回主键

还是使用< insert >标签来写入数据,只不过设置useGeneratedKeys 和keyProperty属性 。

  • useGeneratedKeys:这会令 MyBatis 使⽤ JDBC 的 getGeneratedKeys ⽅法来取出由数据库内部⽣成的主键(⽐如:像 MySQL 和 SQL Server 这样的关系型数据库管理系统的⾃动递增字段),默认值:false.
  • keyProperty:指定能够唯⼀识别对象的属性,MyBatis 会使⽤ getGeneratedKeys 的返回值或 insert 语句的 selectKey ⼦元素设置它的值,默认值:未设置(unset)
<insert id="insertOne" useGeneratedKeys="true" keyProperty="id">
        insert into user_info (username, password, age) values (#{username},#{password},#{age})
    </insert>

测试方法:

    @Test
    void insertOne() {
        UserInfo userInfo = new UserInfo();
        userInfo.setAge(9);
        userInfo.setPassword("999");
        userInfo.setUsername("999");
        Integer result = userMapperXML.insertOne(userInfo);
        System.out.println("增加函数:"+ result+", 增加数据的id:"+userInfo.getId());
    }

结果:

五、删<delete id = >

使用< delete >标签,加上删除的SQL语句即可。

    <delete id="deleteOne">
        delete from user_info where id = #{id}
    </delete>

测试方法:

    @Test
    void deleteOne() {
        userMapperXML.deleteOne(9);
    }

结果:

六、改<update id = >

修改数据直接使用< update >注解,加上修改SQL语句即可。

    <update id="updateOne">
        update user_info set delete_flag = #{deleteFlag} where id = #{id}
    </update>

测试方法:

   @Test
    void updateOne() {
        UserInfo userInfo = new UserInfo();
        userInfo.setId(8);
        userInfo.setDeleteFlag(1);
        userMapperXML.updateOne(userInfo);
    }

结果:

七、查< select id = resultType = >

查询我们只需要使用标签即可。
但是我们也会遇见像前面注解的时候因为字段名和变量名不同而导致映射错误。解决方式与前面也相似。

  • 使用起别名的查询语句,将数据库不同字段名取别名为属性名。
<?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">
<mapper namespace="com.example.springmybatisdemo.mapper.UserMapperXML">

    <select id="selectAll" resultType="com.example.springmybatisdemo.model.UserInfo">
    
        select username , password, age, gender, phone,
        delete_flag as deleteFlag , create_time as createTime, update_time as updateTime
        from user_info
        
    </select>

</mapper>
  • 使用配置文件将数据库字段中使用下划线的蛇形命名转换为小驼峰命名。mybatis.configuration.map-underscore-to-camel-case: true
mybatis:
  configuration:
    map-underscore-to-camel-case: true #配置驼峰⾃动转换
  • 使用标签result和resultMap。在resultMap标签中放入result标签数组,result标签的column属性对应数据库字段,property属性对应类属性名。当其他查询语句需要使用相同的映射时,这需要在select标签的resultMap属性写上resultMap标签的id属性即可。
	<resultMap id="UserMap" type="com.example.springmybatisdemo.model.UserInfo">
        <result column="delete_flag" property="deleteFlag"></result>
        <result column="create_time" property="createTime"></result>
        <result column="update_time" property="updateTime"></result>
    </resultMap>
    
    <select id="selectAll" resultType="com.example.springmybatisdemo.model.UserInfo" resultMap="UserMap">
        select * from user_info
    </select>

到此这篇关于Mybatis XML配置文件实现增删改查的示例代码的文章就介绍到这了,更多相关Mybatis XML增删改查内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家! 

相关文章

  • Java接口和抽象类用法实例总结

    Java接口和抽象类用法实例总结

    这篇文章主要介绍了Java接口和抽象类用法,结合实例形式总结分析了Java接口与抽象类的具体定义、使用技巧与相关注意事项,需要的朋友可以参考下
    2015-12-12
  • Spring AOP原理及动态代理

    Spring AOP原理及动态代理

    这篇文章主要介绍了Spring AOP原理及动态代理,文章通过围绕主题展开详细的内容介绍,具有一定的参考价值,需要的小伙伴可以参考一下
    2022-09-09
  • springboot一个自定义注解如何搞定多线程事务

    springboot一个自定义注解如何搞定多线程事务

    文章介绍了Spring Boot中使用`@Async`注解进行声明式多线程编程的方法,以及如何通过自定义注解和AOP实现多线程事务控制,同时,还解释了`CountDownLatch`的使用场景及其工作原理
    2024-12-12
  • Java Volatile关键字你真的了解吗

    Java Volatile关键字你真的了解吗

    这篇文章主要为大家介绍了Java Volatile关键字,具有一定的参考价值,感兴趣的小伙伴们可以参考一下,希望能够给你带来帮助
    2021-12-12
  • mybatis-plus使用@EnumValue处理枚举类型的示例代码

    mybatis-plus使用@EnumValue处理枚举类型的示例代码

    这篇文章主要介绍了mybatis-plus使用@EnumValue处理枚举类型的示例代码,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧
    2020-09-09
  • Eclipse 出现A configuration with this name already exists问题解决方法

    Eclipse 出现A configuration with this name already exists问题解决方

    这篇文章主要介绍了Eclipse 出现A configuration with this name already exists问题解决方法的相关资料,需要的朋友可以参考下
    2016-11-11
  • 解决SpringBoot跨域的三种方式

    解决SpringBoot跨域的三种方式

    前后端分离是目前的趋势,解决跨域问题也是老生常谈的话题了,我们了解一下什么是域和跨域。域:协议 + 域名 + 端口;三者完全相同则为同域,反之有其一不同均为不同域。跨域请求:当前【发起请求】的域和【请求指向】的域属于不同域时,该次请求称之为跨域请求
    2021-06-06
  • SpringBoot快速迁移至Quarkus的方法步骤

    SpringBoot快速迁移至Quarkus的方法步骤

    这篇文章主要介绍了SpringBoot快速迁移至Quarkus的方法步骤。文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧
    2021-01-01
  • JAVA计算两个日期相差的实例

    JAVA计算两个日期相差的实例

    在java中我找了一下关于计算两个日期之间相差的天数方法有10多种实现方法,下面总结一下常用的几种计算两个日期之间相差的天数实例
    2013-11-11
  • java基于Apache FTP实现文件上传、下载、修改文件名、删除

    java基于Apache FTP实现文件上传、下载、修改文件名、删除

    本篇文章主要介绍了Apache FTP实现文件上传、下载、修改文件名、删除,实现了FTP文件上传(断点续传)、FTP文件下载、FTP文件重命名、FTP文件删除等功能,有需要的可以了解一下。
    2016-11-11

最新评论