当前位置: 首页 > news >正文

【JavaEE】Mybatis XML配置文件实现增删改查

目录

  • 一、环境准备
  • 二、简单启动
  • 三、增< insert id = >
  • 四、返回主键
  • 五、删<delete id = >
  • 六、改<update id = >
  • 七、查< select id = resultType = >

一、环境准备

在使用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 = >

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

  1. 使用起别名的查询语句,将数据库不同字段名取别名为属性名。
<?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>

  1. 使用配置文件将数据库字段中使用下划线的蛇形命名转换为小驼峰命名。mybatis.configuration.map-underscore-to-camel-case: true
mybatis:
  configuration:
    map-underscore-to-camel-case: true #配置驼峰⾃动转换
  1. 使用标签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>
    

相关文章:

  • 编程从键盘输入一个大写英文字符,将其转换为小写字符显示并显示出它的十进制,十六的 ASCI码。
  • Kubernetes集群中部署SonarQube服务
  • Gitee上库常用git命令
  • Babel 从入门到精通(四):@babel/template的应用实例与最佳实践
  • 【JavaEE】springMVC返回Http响应
  • 【负载均衡系列】Nginx
  • 【例6.5】活动选择(信息学奥赛一本通-1323)
  • 如何拆解模糊需求管理
  • 【C语言】自定义数据类型:联合体和枚举
  • Java Collection API增强功能系列之二 List.of、Set.of、Map.of
  • 《Python全栈开发》第12课:RESTful API设计 - 构建现代化接口
  • ArrayList<E>案例//定义一个方法,将价格低于3000的手机信息返回
  • 0324-项目
  • 【蓝桥杯速成】| 11.回溯 之 子集问题
  • SpringBoot星之语明星周边产品销售网站设计与实现
  • 内存管理模块设计与实现
  • 单片机的时钟输出功能-MCO输出(7)
  • Android 13深度定制:揭秘类MIUI全面屏手势返回动效的架构级实现
  • 零知识证明:区块链隐私保护的变革力量
  • python人脸检测、人脸识别、活体检测入门学习教程
  • 习近平会见缅甸领导人敏昂莱
  • 欧盟决意与俄罗斯能源彻底决裂之际,美国谋划新生意:进口俄气对欧转售
  • 保证断电、碰撞等事故中车门系统能够开启!汽车车门把手将迎来强制性国家标准
  • 身临其境感受伟人思想力量,“马克思书房”在上海社科馆揭幕
  • 指挥家高健:东方市民音乐会“高贵不贵”,我愿意常来
  • 长和获准出售巴拿马运河港口以外的港口?外交部:该报道没有依据