Spring Boot入门(7)使用MyBatis操作MySQL

本文涉及的产品
RDS MySQL Serverless 基础系列,0.5-2RCU 50GB
云数据库 RDS MySQL,集群系列 2核4GB
推荐场景:
搭建个人博客
云数据库 RDS MySQL,高可用系列 2核4GB
简介: 介绍 MyBatis 是一款优秀的、开源的持久层框架,它支持定制化 SQL、存储过程以及高级映射。MyBatis 避免了几乎所有的 JDBC 代码和手动设置参数以及获取结果集。

介绍

MyBatis 是一款优秀的、开源的持久层框架,它支持定制化 SQL、存储过程以及高级映射。MyBatis 避免了几乎所有的 JDBC 代码和手动设置参数以及获取结果集。MyBatis 可以使用简单的 XML 或注解来配置和映射原生信息,将接口和 Java 的 POJOs(Plain Old Java Objects,普通的 Java对象)映射成数据库中的记录。

  这就表明,MyBatis是SQL映射框架(SQL mapping framework),和Hibernate工作原理并不相同,因为Hibernate是ORM 框架。
  MyBatis社区已经为Spring Boot提供了starter依赖,因为我们可以在Spring Boot中愉快地使用MyBatis.
  本次介绍将不使用MyBatis XML来执行数据库查询,而是使用基于注释的mappers(annotation-based mappers).

准备工作

  因为本次演示的是如何在Spring Boot中使用MyBatis操作MySQL,进行数据库的增删改查。所以,我们需要对MySQL数据库做一些准备工作。具体说来,就说在MySQL的test数据库下新建表格person,其中的字段为id,name,age,city,id为自增长的主键。

use test

create table person(
id int primary key auto_increment,
name varchar(20),
age int,
city varchar(20)
);
AI 代码解读

  接着在 http://start.spring.io/ 中创建Spring Boot项目,加入Web, MyBatis, MySQL起始依赖,如下图:


项目创建

项目结构

  整个项目的结构如下图:


项目结构

  画红线的框内的文件是我们需要新增或修改的文件。
  先是实体类Person.java,其代码如下:

package com.hello.MyBatisDemo.domain;

public class Person{

    private Integer id;
    private String name;
    private Integer age;
    private String city;

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public Integer getAge() {
        return age;
    }

    public void setAge(Integer age) {
        this.age = age;
    }

    public String getCity() {
        return city;
    }

    public void setCity(String city) {
        this.city = city;
    }

}
AI 代码解读

  接着是基于注释的mappers文件PersonMapper.java,其代码如下:

package com.hello.MyBatisDemo.DAO;

import com.hello.MyBatisDemo.domain.Person;
import org.apache.ibatis.annotations.*;
import java.util.List;

@Mapper
public interface PersonMapper {

    /**
     * 添加操作,返回新增元素的 ID
     * @param person
     */
    @Insert("insert into person(id,name,age,city) values(#{id},#{name},#{age},#{city})")
    @Options(useGeneratedKeys = true, keyColumn = "id", keyProperty = "id")
    void insert(Person person);

    /**
     * 更新操作
     * @param person
     * @return 受影响的行数
     */
    @Update("update person set name=#{name},age=#{age},city=#{city} where id=#{id}")
    Integer update(Person person);

    /**
     * 删除操作
     * @param id
     * @return 受影响的行数
     */
    @Delete("delete from person where id=#{id}")
    Integer delete(@Param("id") Integer id);

    /**
     * 查询所有
     * @return
     */
    @Select("select id,name,age,city from person")
    List<Person> selectAll();

    /**
     * 根据主键查询单个
     * @param id
     * @return
     */
    @Select("select id,name,age,city from person where id=#{id}")
    Person selectById(@Param("id") Integer id);

}
AI 代码解读

  下一步是控制文件PersonController.java,其代码如下:

package com.hello.MyBatisDemo.Controller;

import com.hello.MyBatisDemo.DAO.PersonMapper;
import com.hello.MyBatisDemo.domain.Person;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import java.util.List;

@RestController
public class PersonController {

    @Autowired
    private PersonMapper personMapper;

    @RequestMapping("/insert")
    public String insert(@RequestParam String name,
                         @RequestParam String city,
                         @RequestParam Integer age) {
        Person person = new Person();
        person.setName(name);
        person.setAge(age);
        person.setCity(city);
        personMapper.insert(person);
        return "第"+person.getId()+"条记录插入成功!";
    }

    @RequestMapping("/update")
    public String update(@RequestParam Integer id,
                          @RequestParam String name,
                          @RequestParam String city,
                          @RequestParam Integer age) {
        Person person = new Person();
        person.setId(id);
        person.setName(name);
        person.setAge(age);
        person.setCity(city);
        return personMapper.update(person)+"条记录更新成功!";
    }

    @RequestMapping("/delete")
    public String delete(@RequestParam Integer id) {
        return personMapper.delete(id)+"条记录删除成功!";
    }

    @RequestMapping("/selectById")
    public Person selectById(@RequestParam Integer id) {
        return personMapper.selectById(id);
    }

    @RequestMapping("/selectAll")
    public List<Person> selectAll() {
        return personMapper.selectAll();
    }

}
AI 代码解读

  最后一步是整个项目的配置文件application.properies,主要是MySQL数据库的连接设置,其代码如下:

spring.datasource.url=jdbc:mysql://localhost:33061/test?useUnicode=true&characterEncoding=UTF-8
spring.datasource.username=root
spring.datasource.password=147369
spring.datasource.driver-class-name=com.mysql.jdbc.Driver

server.port=8100
AI 代码解读

  整个项目的结构及代码介绍完毕。

运行及测试

  启动Spring Boot项目,在浏览器中输入: http://localhost:8100/insert?name=bob&age=14&city=shanghai 即可插入一条新的记录。如此类似地插入以下三条记录:


插入记录

  在浏览器中输入: http://localhost:8100/update?id=2&name=tian&age=27&city=shanghai 即可更新id=2的记录
  在浏览器中输入: http://localhost:8100/delete?id=3 即可删除id=3的记录。
  在浏览器中输入: http://localhost:8100/selectById?id=2 即可查询id=2的记录。
  在浏览器中输入: http://localhost:8100/selectAll 即可查询所有的记录。
  本次分享到此结束,接下来还会继续分享更多的关于Spring Boot的内容,欢迎大家交流~~

相关实践学习
如何快速连接云数据库RDS MySQL
本场景介绍如何通过阿里云数据管理服务DMS快速连接云数据库RDS MySQL,然后进行数据表的CRUD操作。
全面了解阿里云能为你做什么
阿里云在全球各地部署高效节能的绿色数据中心,利用清洁计算为万物互联的新世界提供源源不断的能源动力,目前开服的区域包括中国(华北、华东、华南、香港)、新加坡、美国(美东、美西)、欧洲、中东、澳大利亚、日本。目前阿里云的产品涵盖弹性计算、数据库、存储与CDN、分析与搜索、云通信、网络、管理与监控、应用服务、互联网中间件、移动服务、视频服务等。通过本课程,来了解阿里云能够为你的业务带来哪些帮助 &nbsp; &nbsp; 相关的阿里云产品:云服务器ECS 云服务器 ECS(Elastic Compute Service)是一种弹性可伸缩的计算服务,助您降低 IT 成本,提升运维效率,使您更专注于核心业务创新。产品详情: https://www.aliyun.com/product/ecs
相关文章
微服务——SpringBoot使用归纳——Spring Boot集成MyBatis——基于 xml 的整合
本教程介绍了基于XML的MyBatis整合方式。首先在`application.yml`中配置XML路径,如`classpath:mapper/*.xml`,然后创建`UserMapper.xml`文件定义SQL映射,包括`resultMap`和查询语句。通过设置`namespace`关联Mapper接口,实现如`getUserByName`的方法。Controller层调用Service完成测试,访问`/getUserByName/{name}`即可返回用户信息。为简化Mapper扫描,推荐在Spring Boot启动类用`@MapperScan`注解指定包路径避免逐个添加`@Mapper`
44 0
SpringBoot 通过集成 Flink CDC 来实时追踪 MySql 数据变动
通过详细的步骤和示例代码,您可以在 SpringBoot 项目中成功集成 Flink CDC,并实时追踪 MySQL 数据库的变动。
431 43
微服务——SpringBoot使用归纳——Spring Boot集成MyBatis——基于注解的整合
本文介绍了Spring Boot集成MyBatis的两种方式:基于XML和注解的形式。重点讲解了注解方式,包括@Select、@Insert、@Update、@Delete等常用注解的使用方法,以及多参数时@Param注解的应用。同时,针对字段映射不一致的问题,提供了@Results和@ResultMap的解决方案。文章还提到实际项目中常结合XML与注解的优点,灵活使用两者以提高开发效率,并附带课程源码供下载学习。
33 0
微服务——SpringBoot使用归纳——Spring Boot集成MyBatis——MyBatis 介绍和配置
本文介绍了Spring Boot集成MyBatis的方法,重点讲解基于注解的方式。首先简述MyBatis作为持久层框架的特点,接着说明集成时的依赖导入,包括`mybatis-spring-boot-starter`和MySQL连接器。随后详细展示了`properties.yml`配置文件的内容,涵盖数据库连接、驼峰命名规范及Mapper文件路径等关键设置,帮助开发者快速上手Spring Boot与MyBatis的整合开发。
94 0
对Spring、SpringMVC、MyBatis框架的介绍与解释
Spring 框架提供了全面的基础设施支持,Spring MVC 专注于 Web 层的开发,而 MyBatis 则是一个高效的持久层框架。这三个框架结合使用,可以显著提升 Java 企业级应用的开发效率和质量。通过理解它们的核心特性和使用方法,开发者可以更好地构建和维护复杂的应用程序。
171 29
Java后端开发-使用springboot进行Mybatis连接数据库步骤
本文介绍了使用Java和IDEA进行数据库操作的详细步骤,涵盖从数据库准备到测试类编写及运行的全过程。主要内容包括: 1. **数据库准备**:创建数据库和表。 2. **查询数据库**:验证数据库是否可用。 3. **IDEA代码配置**:构建实体类并配置数据库连接。 4. **测试类编写**:编写并运行测试类以确保一切正常。
135 2
Spring Boot 3 整合 Mybatis-Plus 实现数据权限控制
本文介绍了如何在Spring Boot 3中整合MyBatis-Plus实现数据权限控制,通过使用MyBatis-Plus提供的`DataPermissionInterceptor`插件,在不破坏原有代码结构的基础上实现了细粒度的数据访问控制。文中详细描述了自定义注解`DataScope`的使用方法、`DataPermissionHandler`的具体实现逻辑,以及根据用户的不同角色和部门动态添加SQL片段来限制查询结果。此外,还展示了基于Spring Boot 3和Vue 3构建的前后端分离快速开发框架的实际应用案例,包括项目的核心功能模块如用户管理、角色管理等,并提供Gitee上的开源仓库
598 11
java版药品不良反应智能监测系统源码,采用SpringBoot、Vue、MySQL技术开发
基于B/S架构,采用Java、SpringBoot、Vue、MySQL等技术自主研发的ADR智能监测系统,适用于三甲医院,支持二次开发。该系统能自动监测全院患者药物不良反应,通过移动端和PC端实时反馈,提升用药安全。系统涵盖规则管理、监测报告、系统管理三大模块,确保精准、高效地处理ADR事件。
232 1
如何将Spring Boot + MySQL应用程序部署到Pivotal Cloud Foundry (PCF)
如何将Spring Boot + MySQL应用程序部署到Pivotal Cloud Foundry (PCF)
105 5
深入实践springboot实战 蓄势待发 我不是雷锋 我是知识搬运工
springboot,说白了就是一个集合了功能的大类库,包括springMVC,spring,spring data,spring security等等,并且提供了很多和可以和其他常用框架,插件完美整合的接口(只能说是一些常用框架,基本在github上能排上名次的都有完美整合,但如果是自己写的一个框架就无法实现快速整合)。

热门文章

最新文章