Springboot-数据库操作(Mybatis)-初级入门

文章介绍了如何在SpringBoot项目中集成MyBatis-Plus进行数据库操作,包括引入依赖、配置数据库信息、创建实体类和Mapper接口,以及Services和Controller层的构建。示例展示了用户信息的增删改查操作。同时提到了SpringDataJPA和传统XML方式作为对比。
摘要由CSDN通过智能技术生成

一、Mybatis-plus介绍

官方文档:简介 | MyBatis-Plus (baomidou.com)

 他只增强了单表查询,没增强多表查询等复杂的查询。

二、配置

引入依赖

      <!--        MyBatisPlus依赖-->
        <dependency>
            <groupId>com.baomidou</groupId>
            <artifactId>mybatis-plus-boot-starter</artifactId>
            <version>3.4.2</version>
        </dependency>

        <!--        mysql驱动依赖-->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.47</version>
        </dependency>

        <!--        数据链接池 druid-->
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>druid-spring-boot-starter</artifactId>
            <version>1.1.20</version>
        </dependency>

配置数据库相关信息

spring.datasource.type=com.alibaba.druid.pool.DruidDataSource
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
spring.datasource.url=jdbc:mysql://localhost:3306/springboot  #数据库名
spring.datasource.username=root   #账号
spring.datasource.password=****** #密码
mybatis-plus.configuration.log-impl=org.apache.ibatis.logging.stdout.StdOutImpl

添加@MapperScan注解

         创建UserMapper接口,这也是项目的持久层,与数据查询相关的,之后我们需要让sprongboot知道,mapper文件夹就是数据持久层接口,所以,在项目入口文件中还要使用@MapperScan注解定义持久层。

三、程序架构

下面以一个用户信息查询需求为例,数据库字段如图所示:

3.1 实体类

先定义一个user类,包含变量id,username,password,birthday 

package com.example.springboot1_2.entity;

import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableField;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableName;

import java.util.List;

@TableName("t_user")  //其对应数据库的表名
public class User {
    @TableId(type = IdType.AUTO)
    private int id;
    private String username;
    private String password;
    private String birthday;


   
    public int getId() {
        return id;
    }

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

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    public String getBirthday() {
        return birthday;
    }

    public void setBirthday(String birthday) {
        this.birthday = birthday;
    }

    @Override
    public String toString() {
        return "User{" +
                "id=" + id +
                ", username='" + username + '\'' +
                ", password='" + password + '\'' +
                ", birthday='" + birthday + '\'' +
                '}';
    }
}

3.2 定义dao/Mapper层

        里面定义了数据库查询的语句,下面定义了一个接口,正常情况下需要写他的实现函数,但是Mybatis-plus针对单表查询进行了增强,直接加注解即可,不需要我们实现。

package com.example.springboot1_2.mapper;

import com.example.springboot1_2.entity.User;
import org.apache.ibatis.annotations.*;

import java.util.List;

@Mapper
public interface UserMapper {

    //    查询所有用户
    @Select("select * from user")
    public List<User> findAllUser();

    //  插入数据
    @Insert("insert into user values (#{id},#{username},#{password},#{birthday})")
    public int insert(User user);

    //    删除用户
    @Delete("delete from user where id=#{id}")
    int delete(int id);

    //    更新用户
    @Update("update user set username=#{username},password=#{password},birthday=#{birthday} where id=#{id}")
    int update(User user);
}

 3.3 定义Services层次

        这一层是系统的核心功能,包含系统最核心的数据处理编排。下面只是个简单的查询功能,直接调用UserMapper层的查询函数即可。

package com.example.springboot1_2.services;

import com.example.springboot1_2.entity.User;
import com.example.springboot1_2.mapper.UserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class UserService {
    @Autowired
    private UserMapper userMapper;
    
    public List<User> UserService(){
        return userMapper.findAllUser();
    }
}

 3.4 controller

定义对外交互层controller,提供一个url调用查询用户的服务。

package com.example.springboot1_2.controller;

import com.example.springboot1_2.entity.User;
import com.example.springboot1_2.mapper.UserMapper;
import com.example.springboot1_2.services.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

@RestController
public class UserController {

    private UserService Service;

    @GetMapping("/user")
    public List query() {
        List<User> userList = Service.UserService();
        if (userList != null)
            return userList;
    }
}

四、其他方法

        数据存取结构类似,但是他将sql存到了专门的xml文件中,据说是一种比较老的方法。但是感觉逻辑很清晰。

(1条消息) SpringBoot-数据库的查询_thzan的博客-CSDN博客_springboot查询数据库 

 并未使用mybatis,而是使用的Spring Data JPA包,但是数据存取结构依旧类似,看了一些数据持久层框架,例如(JPA、Hibernate和Mybatis),系统的数据结构是一样的,都是controller->Services->Dao/Mapper->实体类->数据库。只是Dao/Mapper层与数据库交互的步骤有一些区别,不影响上层的contorller层和Services。

基于spring boot后端读取数据库数据_eat_Cookie的博客-CSDN博客_springboot读取数据库中的值 

  • 1
    点赞
  • 13
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
Spring Boot是一个用于创建独立的、基于Spring的应程序的框架。它简化了Spring应用程序的配置和部署过程,并提供了一套强大的开发工具和约定,使开发人员能够更快地构建高效的应用程序。 MyBatis是一个开源的持久层框架,它可以将SQL语句和数据库操作映射到Java对象中,使得开发人员可以通过简单的配置来实现数据访问层的操作。在Spring Boot中集成MyBatis可以通过添加相应的依赖和配置来实现。 PageHelper是一个用于实现分页功能的MyBatis插件。它可以通过拦截SQL语句并自动添加分页查询的相关信息,从而简化了分页查询的操作。在Spring Boot中集成PageHelper可以通过添加相应的依赖和配置来实现。 Swagger是一个用于生成、描述、调用和可视化RESTful风格的Web服务的工具集。它可以根据代码注解自动生成接口文档,并提供了一个用户友好的界面来测试和调试接口。在Spring Boot中集成Swagger可以通过添加相应的依赖和配置来实现。 下面是集成Spring BootMyBatis、PageHelper和Swagger的步骤: 1. 在pom.xml文件中添加Spring BootMyBatis、PageHelper和Swagger的依赖: ```xml <dependencies> <!-- Spring Boot --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <!-- MyBatis --> <dependency> <groupId>org.mybatis.spring.boot</groupId> <artifactId>mybatis-spring-boot-starter</artifactId> </dependency> <!-- PageHelper --> <dependency> <groupId>com.github.pagehelper</groupId> <artifactId>pagehelper-spring-boot-starter</artifactId> </dependency> <!-- Swagger --> <dependency> <groupId>io.springfox</groupId> <artifactId>springfox-swagger2</artifactId> <version>2.9.2</version> </dependency> <dependency> <groupId>io.springfox</groupId> <artifactId>springfox-swagger-ui</artifactId> <version>2.9.2</version> </dependency> </dependencies> ``` 2. 在application.properties或application.yml文件中配置数据库连接和MyBatis的相关配置: ```properties # 数据库连接配置 spring.datasource.url=jdbc:mysql://localhost:3306/mydatabase spring.datasource.username=root spring.datasource.password=123456 spring.datasource.driver-class-name=com.mysql.jdbc.Driver # MyBatis配置 mybatis.mapper-locations=classpath:mapper/*.xml mybatis.type-aliases-package=com.example.model # PageHelper配置 pagehelper.helper-dialect=mysql pagehelper.reasonable=true pagehelper.support-methods-arguments=true # Swagger配置 swagger.enabled=true ``` 3. 创建MyBatis的Mapper接口和对应的XML文件,定义数据库操作的SQL语句和映射关系。 4. 创建Spring Boot的Controller,定义接口的请求路径和处理方法。 5. 在启动上添加@EnableSwagger2注解,启用Swagger。 ```java @SpringBootApplication @EnableSwagger2 public class Application { public static void main(String[] args) { SpringApplication.run(Application.class, args); } } ``` 6. 启动应用程序,访问http://localhost:8080/swagger-ui.html可以查看生成的接口文档,并进行接口的测试和调试。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

ad_m1n

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值