SpringBoot整合Mybatis简单实现增删改查

下面是关于SpringBoot整合Mybatis实现增删改查的详细攻略:

1. 环境搭建

在开始之前,你需要在本地安装好以下软件:

  • JDK 1.8或以上版本
  • Maven
  • MySQL数据库

在安装好上述软件后,你可以新建一个SpringBoot项目,这里使用的是IntelliJ IDEA,你可以通过IDEA创建SpringBoot项目并选择添加Mybatis Starter依赖,如下所示:

<dependency>
    <groupId>org.mybatis.spring.boot</groupId>
    <artifactId>mybatis-spring-boot-starter</artifactId>
    <version>${mybatis-spring-boot.version}</version>
</dependency>

2. 数据库配置

接下来,我们需要在application.properties文件中配置数据库相关的信息,该文件路径为:src/main/resources/application.properties。在文件中添加以下内容:

# 数据源配置
spring.datasource.url=jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=UTF-8&serverTimezone=Asia/Shanghai
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
spring.datasource.username=root
spring.datasource.password=123456

# MyBatis配置
mybatis.type-aliases-package=com.example.entity
mybatis.mapper-locations=classpath:mapper/*Mapper.xml

其中,spring.datasource.url为数据库连接地址,spring.datasource.usernamespring.datasource.password为数据库账号和密码,mybatis.type-aliases-package为实体类所在的包名,mybatis.mapper-locations为mapper接口所在的包名。

在完成数据库配置后,可以在IDEA中依次右击工程名称->Maker Directory as ->Resources Folder,创建一个resources文件夹。

3. 实体类和Mapper接口文件

接下来,我们需要创建实体类和Mapper接口文件。首先是实体类,在com.example.entity包下新建一个User实体类:

public class User {
    private Long id;
    private String name;
    private Integer age;
    // 省略getter和setter方法
}

然后,我们需要新建一个Mapper接口,该接口位于com.example.mapper包下,示例如下:

@Mapper
@Repository
public interface UserMapper {
    User selectByPrimaryKey(Long id);

    int insert(User user);

    int updateByPrimaryKey(User user);

    int deleteByPrimaryKey(Long id);
}

需要注意的是,在UserMapper接口上添加@Mapper注解,表示该接口是Mybatis的Mapper接口;而@Repository注解则表示该类是一个Repository Bean。

在创建Mapper接口后,需要在resources文件夹下新建一个mapper文件夹,并在该文件夹下添加UserMapper.xml文件,示例如下:

<!DOCTYPE mapper
    PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
    "http://mybatis.org/dtd/mybatis-3-mapper.dtd">

<mapper namespace="com.example.mapper.UserMapper">

    <select id="selectByPrimaryKey" resultType="com.example.entity.User">
        select * from user where id = #{id}
    </select>

    <insert id="insert" parameterType="com.example.entity.User">
        insert into user(name, age) values(#{name}, #{age})
    </insert>

    <update id="updateByPrimaryKey" parameterType="com.example.entity.User">
        update user set name=#{name},age=#{age} where id=#{id}
    </update>

    <delete id="deleteByPrimaryKey" parameterType="java.lang.Long">
        delete from user where id =#{id}
    </delete>

</mapper>

selectinsertupdatedelete标签中,id属性为对应的Mapper接口中方法名,parameterType属性为Mapper接口方法的参数类型,resultType属性为查询结果的实体类类型。

4. Service层

接下来,我们需要新建一个Service接口和实现类,在com.example.service包下创建UserService接口,示例如下:

public interface UserService {
    User selectByPrimaryKey(Long id);

    int insert(User user);

    int updateByPrimaryKey(User user);

    int deleteByPrimaryKey(Long id);
}

然后,在com.example.service.impl包下创建UserServiceImpl类,示例如下:

@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private UserMapper userMapper;

    @Override
    public User selectByPrimaryKey(Long id) {
        return userMapper.selectByPrimaryKey(id);
    }

    @Override
    public int insert(User user) {
        return userMapper.insert(user);
    }

    @Override
    public int updateByPrimaryKey(User user) {
        return userMapper.updateByPrimaryKey(user);
    }

    @Override
    public int deleteByPrimaryKey(Long id) {
        return userMapper.deleteByPrimaryKey(id);
    }
}

需要注意的是,在UserServiceImpl类上添加@Service注解,表示该类是一个Service Bean。同时,我们在该类中注入了UserMapper接口,使用该接口中的方法来操作数据库。

5. Controller层

最后,我们需要在com.example.controller包下创建一个UserController类,示例如下:

@RestController
@RequestMapping("/user")
public class UserController {

    @Autowired
    private UserService userService;

    @GetMapping("/{id}")
    public User selectByPrimaryKey(@PathVariable("id") Long id) {
        return userService.selectByPrimaryKey(id);
    }

    @PostMapping("")
    public int insert(@RequestBody User user) {
        return userService.insert(user);
    }

    @PutMapping("")
    public int updateByPrimaryKey(@RequestBody User user) {
        return userService.updateByPrimaryKey(user);
    }

    @DeleteMapping("/{id}")
    public int deleteByPrimaryKey(@PathVariable("id") Long id) {
        return userService.deleteByPrimaryKey(id);
    }
}

需要注意的是,在UserController类上添加@RestController注解,表示该类是一个处理HTTP请求的Controller Bean。在类中注入了UserService接口,并在方法中调用该接口中的方法。

6. 代码测试

在完成上述操作后,我们已经可以在浏览器中访问http://localhost:8080/user/1来查询用户ID为1的记录了。现在,我们可以使用Postman来进行增、删、改操作。示例如下:

插入记录

  • 请求方式:POST
  • URL:http://localhost:8080/user
  • 请求头:Content-Type: application/json
  • 请求体:
{
    "name": "test",
    "age": 25
}

更新记录

  • 请求方式:PUT
  • URL:http://localhost:8080/user
  • 请求头:Content-Type: application/json
  • 请求体:
{
    "id": 1,
    "name": "update",
    "age": 30
}

删除记录

  • 请求方式:DELETE
  • URL:http://localhost:8080/user/1

至此,我们完成了SpringBoot整合Mybatis简单实现增删改查的攻略。在实际开发中,我们还可以通过分页和条件查询等方式来增强用户操作体验。

本站文章如无特殊说明,均为本站原创,如若转载,请注明出处:SpringBoot整合Mybatis简单实现增删改查 - Python技术站

(0)
上一篇 2023年5月19日
下一篇 2023年5月19日

相关文章

  • 一文带你学习Java中的线程

    一文带你学习Java中的线程 什么是线程 线程是操作系统能够进行运算调度的最小单位。也就是说,线程是进程中的一个实体,是被系统独立调度和分配CPU时间的基本单位,是比进程更小的能独立运行的基本单位。 在Java中,线程是一个单独的执行路径,每个线程都有自己的栈和程序计数器。JVM运行线程调度,每个线程的执行顺序和时间是由操作系统决定。 如何创建线程 在Jav…

    Java 2023年5月23日
    00
  • Java实现ModbusTCP通信功能

    让我来详细讲解Java实现ModbusTCP通信功能的攻略。 简介 Modbus是一种通信协议,用于市场上常见的工业控制系统。这种协议使用Modbus通信协议功能码来读写数据,通常采用RS-485或RS-232串行通信。而Modbus TCP是Modbus协议的一种,它使用TCP/IP网络来实现通信。 如果你想在Java中实现ModbusTCP通信功能,你需…

    Java 2023年5月19日
    00
  • Apache Hudi结合Flink的亿级数据入湖实践解析

    Apache Hudi 是什么? Apache Hudi 是 Apache 基金会下的开源项目,它提供了一个数据湖解决方案,支持增量式的数据处理和可变的数据表现形式。Hudi 最初由 Ubiquiti 区块链团队在 2016 年开发,2019 年捐赠给 Apache 软件基金会。Hudi 的核心特性是 Delta Lake 和 Apache Kafka 支持…

    Java 2023年6月2日
    00
  • IntelliJ IDEA的数据库管理工具实在太方便了(推荐)

    下面就为您详细讲解如何使用IntelliJ IDEA的数据库管理工具。 第一步:打开IntelliJ IDEA,点击菜单栏上的“View”->“Tool Windows”->“Database”打开数据库管理面板。 第二步:点击“Add”按钮,选择需要连接的数据库类型(MySQL、Oracle等),填写数据库的连接信息,点击“Test Conne…

    Java 2023年5月20日
    00
  • Spring Security配置多个数据源并添加登录验证码的实例代码

    下面是详细讲解Spring Security配置多个数据源并添加登录验证码的实例代码的完整攻略: 什么是Spring Security? Spring Security是针对基于Spring的应用程序的安全框架,它提供了一组可以在应用程序中使用的安全服务,例如身份验证和授权。 Spring Security配置多个数据源并添加登录验证码的步骤 第一步:添加依…

    Java 2023年5月20日
    00
  • 详解SpringBoot修改启动端口server.port的四种方式

    下面是详解SpringBoot修改启动端口server.port的四种方式的完整攻略: 方式一:通过application.properties文件修改 在SpringBoot应用的classpath路径下添加application.properties文件,然后在文件中添加以下内容: server.port=8081 这样就可以将应用的启动端口修改为808…

    Java 2023年5月26日
    00
  • struts2入门Demo示例

    下面为你详细讲解“struts2入门Demo示例”的完整攻略: 环境搭建 首先,需要搭建Java环境和Tomcat服务器环境,并下载Struts2框架。这里以Windows环境下为例,具体步骤如下: 安装Java环境 下载JDK并进行安装,自定义安装目录。 配置环境变量JAVA_HOME,值为JDK安装目录路径,例如 C:\Program Files\Jav…

    Java 2023年5月20日
    00
  • IDEA工程运行时总是报xx程序包不存在实际上包已导入(问题分析及解决方案)

    问题背景 在使用 JetBrains 旗下的 Java IDE 工具 IntelliJ IDEA 进行项目开发时,有时会遇到一个问题:在导入了某些依赖库后,运行程序时提示某些类找不到或某些程序包不存在,但实际上这些包已经被正确导入了。 问题原因 这是因为 IntelliJ IDEA 默认会在编译、运行时根据 Maven、Gradle 或自己所设置的依赖路径自…

    Java 2023年5月26日
    00
合作推广
合作推广
分享本页
返回顶部