首页 > 其他分享 >使用Spring Boot集成MyBatis

使用Spring Boot集成MyBatis

时间:2024-07-15 10:11:02浏览次数:9  
标签:Spring Boot public User MyBatis import id user

使用Spring Boot集成MyBatis

大家好,我是微赚淘客系统3.0的小编,是个冬天不穿秋裤,天冷也要风度的程序猿!今天我们来探讨如何在Spring Boot项目中集成MyBatis,实现持久化操作与数据库的交互。MyBatis是一个优秀的持久层框架,结合Spring Boot能够快速、高效地开发数据库访问功能。

1. 集成MyBatis

在Spring Boot项目中集成MyBatis,首先需要引入相应的依赖。在pom.xml中添加以下依赖:

<dependency>
    <groupId>org.mybatis.spring.boot</groupId>
    <artifactId>mybatis-spring-boot-starter</artifactId>
    <version>2.2.0</version>
</dependency>
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-jdbc</artifactId>
</dependency>
<dependency>
    <groupId>mysql</groupId>
    <artifactId>mysql-connector-java</artifactId>
    <version>8.0.26</version>
</dependency>

这里引入了mybatis-spring-boot-starter用于集成MyBatis和Spring Boot,spring-boot-starter-jdbc用于支持JDBC操作,以及MySQL数据库的驱动。

2. 配置数据源和MyBatis

application.propertiesapplication.yml中配置数据源和MyBatis相关属性:

spring.datasource.url=jdbc:mysql://localhost:3306/testdb
spring.datasource.username=root
spring.datasource.password=password

mybatis.mapper-locations=classpath*:mapper/*.xml

这里配置了数据库连接信息和MyBatis的Mapper文件路径。

3. 编写Mapper接口和Mapper XML文件

创建一个MyBatis的Mapper接口和对应的Mapper XML文件来定义SQL语句和映射关系。假设我们有一个User表,示例代码如下:

package cn.juwatech.mapper;

import cn.juwatech.entity.User;
import org.apache.ibatis.annotations.*;

import java.util.List;

@Mapper
public interface UserMapper {

    @Select("SELECT * FROM users")
    List<User> findAll();

    @Select("SELECT * FROM users WHERE id = #{id}")
    User findById(Long id);

    @Insert("INSERT INTO users(name, email) VALUES(#{name}, #{email})")
    @Options(useGeneratedKeys = true, keyProperty = "id")
    void insert(User user);

    @Update("UPDATE users SET name = #{name}, email = #{email} WHERE id = #{id}")
    void update(User user);

    @Delete("DELETE FROM users WHERE id = #{id}")
    void delete(Long id);
}

上述代码中,我们定义了对User表进行增删改查的操作,使用了注解方式配置SQL语句。

4. 创建Service层

编写一个Service层来调用Mapper接口中定义的方法,处理业务逻辑:

package cn.juwatech.service;

import cn.juwatech.entity.User;
import cn.juwatech.mapper.UserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
@Transactional
public class UserService {

    @Autowired
    private UserMapper userMapper;

    public List<User> findAllUsers() {
        return userMapper.findAll();
    }

    public User findUserById(Long id) {
        return userMapper.findById(id);
    }

    public void saveUser(User user) {
        if (user.getId() == null) {
            userMapper.insert(user);
        } else {
            userMapper.update(user);
        }
    }

    public void deleteUser(Long id) {
        userMapper.delete(id);
    }
}

在Service层中,我们注入了UserMapper,并定义了对应的业务方法,用于处理用户信息的增删改查操作。

5. 编写Controller层

最后,编写一个Controller层来处理HTTP请求,并调用Service层的方法进行业务处理:

package cn.juwatech.controller;

import cn.juwatech.entity.User;
import cn.juwatech.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

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

    @Autowired
    private UserService userService;

    @GetMapping
    public List<User> getAllUsers() {
        return userService.findAllUsers();
    }

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

    @PostMapping
    public void createUser(@RequestBody User user) {
        userService.saveUser(user);
    }

    @PutMapping("/{id}")
    public void updateUser(@PathVariable("id") Long id, @RequestBody User user) {
        user.setId(id);
        userService.saveUser(user);
    }

    @DeleteMapping("/{id}")
    public void deleteUser(@PathVariable("id") Long id) {
        userService.deleteUser(id);
    }
}

在Controller层中,我们使用了@RestController@RequestMapping注解来定义RESTful风格的接口,通过调用UserService来处理业务逻辑。

6. 总结

本文详细介绍了如何在Spring Boot项目中集成MyBatis,通过配置依赖、数据源、Mapper接口和XML文件,实现了基本的数据库操作。通过示例代码演示了如何定义Mapper接口、编写SQL语句和配置Service层、Controller层,完整展示了Spring Boot集成MyBatis的开发流程和最佳实践。

著作权归聚娃科技微赚淘客系统开发者团队,转载请注明出处!

标签:Spring,Boot,public,User,MyBatis,import,id,user
From: https://www.cnblogs.com/szk123456/p/18302557

相关文章

  • 使用Spring Security实现安全认证
    使用SpringSecurity实现安全认证大家好,我是微赚淘客系统3.0的小编,是个冬天不穿秋裤,天冷也要风度的程序猿!在这篇文章中,我将详细介绍如何使用SpringSecurity实现安全认证。通过丰富的代码示例,帮助大家全面掌握SpringSecurity的核心功能和配置方法。1.SpringSecurity概述Spri......
  • Auto run after booting up OS
    ToexecuteascriptautomaticallyafterbootinguptoUbuntuOS,youcanplacethescriptinthe/etc/rc.localfileorcreateasystemdservice.Here'showtodoitusingbothmethods:Method1:Using/etc/rc.localOpenthe/etc/rc.localfilewithr......
  • Spring框架--个人笔记
    1.什么是spring框架1.spring是一款开源框架,解决企业开发的复杂性。2.spring框架提供了三大核心思想:IOC、AOP、DIIOC:控制反转。创建对象并管理生命周期。AOP:面向切面编程。不改变源码对代码进行扩展。DI:依赖注入。3.spring框架特点:1.方便解耦,简化开发。2.AOP编程的支持-......
  • Spring Boot集成grpc快速入门demo
    1.什么是GRPC?gRPC 是一个高性能、开源、通用的RPC框架,由Google推出,基于HTTP2协议标准设计开发,默认采用ProtocolBuffers数据序列化协议,支持多种开发语言。gRPC提供了一种简单的方法来精确的定义服务,并且为客户端和服务端自动生成可靠的功能库。在gRPC客户端可以直接调用不同......
  • SpringBoot+dynamic+druid的多数据源配置
    一、模块环境SpringBoot版本:2.7.12MySQL版本:8.0.33Druid版本:1.2.23Dynamic版本:3.6.1二、数据源配置文件spring:autoconfigure:#排除Druid自动配置exclude:com.alibaba.druid.spring.boot.autoconfigure.DruidDataSourceAutoConfiguredatasource:......
  • 基于java+springboot+vue实现的健身房管理系统(文末源码+Lw)113
     基于SpringBoot+Vue的实现的健身房管理系统(源码+数据库+万字Lun文+流程图+ER图+结构图+演示视频+软件包)系统功能:本健身房管理系统管理员,会员,员工。管理员功能有个人中心,会员管理,员工管理,会员卡管理,会员卡类型管理,教练信息管理,解聘管理,健身项目管理,指导项目管理,健身器材管......
  • 基于java+springboot+vue实现的在线教育系统(文末源码+Lw)111
     基于SpringBoot+Vue的实现的在线教育系统(源码+数据库+万字Lun文+流程图+ER图+结构图+演示视频+软件包)系统功能:本在线教育系统管理员功能有个人中心,用户管理,讲师管理,普通管理员管理,课程管理员管理,课程管理,课程分类管理,教师管理,名师管理,系统管理,订单管理。普通管理员和课......
  • Spring源码分析
    01、Spring源码分析:initPropertySources方法扩展点Spring的强大之处不仅仅在于它为Java开发者提供了极大便利,更在于它的开放式架构,使得用户可以拥有最大扩展Spring的能力。protectedvoidinitPropertySources(){ //Forsubclasses:donothingbydefault. }在A......
  • Spring源码分析
    01、Spring源码分析:initPropertySources方法扩展点Spring的强大之处不仅仅在于它为Java开发者提供了极大便利,更在于它的开放式架构,使得用户可以拥有最大扩展Spring的能力。protectedvoidinitPropertySources(){ //Forsubclasses:donothingbydefault. }在Abstrac......
  • 基于SpringBoot+Hadoop+python的物品租赁系统(带1w+文档)
    基于SpringBoot+Hadoop+python的物品租赁系统(带1w+文档)基于SpringBoot+Hadoop+python的物品租赁系统(带1w+文档)物品租赁系统是电子、信息技术相结合,是一种必然的发展趋势。以互联网为基础,以服务于广大用户为目的,发展整体优势,扩大规模,提升服务质量,提高物品租赁的......