SpringBoot框架连接数据库实战(超详细)

2023-05-16

SpringBoot框架用于实战(可直接下载源码进行拓展)



步骤:

  1. 创建数据库mr_wen,新建两条测试数据
  2. 创建SpringBoot项目
  3. 编写代码块,并进行单元测试

    创建数据库mr_wen,新建两条测试数据

 

  • create DATABASE mr_wen;
    use mr_wen;
    create table `product_category` (
        `category_id` int not null auto_increment,
        `category_name` varchar(64) not null ,
        `category_type` int not null  ,
        primary key (`category_id`)
    );

    创建SpringBoot项目(图解)

     创建项目

     创建完成


     编写代码块

  • 检查并导入依赖(pom.xml)
  • <dependencies>
           <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-starter-web</artifactId>
            </dependency>
    
            <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-starter-test</artifactId>
                <scope>test</scope>
            </dependency>
    
            <dependency>
                <groupId>mysql</groupId>
                <artifactId>mysql-connector-java</artifactId>
            </dependency>
    
            <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-starter-data-jpa</artifactId>
            </dependency>
    
            <dependency>
                <groupId>org.projectlombok</groupId>
                <artifactId>lombok</artifactId>
            </dependency>
        </dependencies>
    
  • 测试项目是否可运行
  • 编写application.properties(用于连接数据库)
  • Spring.dataSource.driver-class-name=com.mysql.cj.jdbc.Driver
    Spring.dataSource.url=jdbc:mysql://localhost:3306/mr_wen?serverTimezone=UTC&characterEncoding=utf-8&useSSL=false
    Spring.dataSource.username=root
    Spring.dataSource.password=root
    
    Spring.jpa:shop-sql:true
    
    
  • com.example.demo目录下创建包名dataobject,并创建类ProductCategory实体类
  • package com.example.demo.dataobject;
    
    import lombok.Data;
    
    import javax.persistence.Entity;
    import javax.persistence.GeneratedValue;
    import javax.persistence.GenerationType;
    import javax.persistence.Id;
    //需要idea安装lombok插件,也可以自行添加G/S方法,toStirng方法
    @Entity
    @Data
    public class ProductCategory {
    
        @Id
        @GeneratedValue(strategy = GenerationType.IDENTITY)
        private Integer categoryId;
    
    
        private String categoryName;
    
        private Integer categoryType;
    
    
    }
    
  •  com.example.demo目录下创建包名dao,并创建类ProductCategoryDao持久层
  • package com.example.demo.dao;
    
    import com.example.demo.dataobject.ProductCategory;
    import org.springframework.data.jpa.repository.JpaRepository;
    
    public interface ProductCategoryDao extends JpaRepository<ProductCategory,Integer> {
        List<ProductCategory> findByCategoryTypeIn(List<Integer> categoryTypeList);
    }
  • 进行测试(写完程序进行单元测试可以随时检验代码的错误)
  • package com.example.demo.dao;
    
    import com.example.demo.dataobject.ProductCategory;
    import org.junit.Assert;
    import org.junit.Test;
    import org.junit.runner.RunWith;
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.boot.test.context.SpringBootTest;
    import org.springframework.test.context.junit4.SpringRunner;
    
    import java.util.Arrays;
    import java.util.List;
    
    import static org.junit.Assert.*;
    
    @RunWith(SpringRunner.class)
    @SpringBootTest
    public class ProductCategoryDaoTest {
    
        @Autowired
        private ProductCategoryDao productCategoryDao;
    
        /*查询*/
        @Test
        public void findOne(){
            ProductCategory productCategory=productCategoryDao.findById(1).get();
            Assert.assertNotNull(productCategory);
            System.out.println("productCategory = " + productCategory);
        }
    
        /*测试新增数据*/
        @Test
        public void saveTest(){
            ProductCategory productCategory=new ProductCategory();
            productCategory.setCategoryName("最佳科技榜单");
            productCategory.setCategoryType(1);
            productCategoryDao.save(productCategory);
        }
    
        /*测试更新*/
        @Test
        public void updateTest(){
            ProductCategory productCategory=new ProductCategory();
            productCategory.setCategoryId(2);
            productCategory.setCategoryName("科技榜单");
            productCategory.setCategoryType(10);
            productCategoryDao.save(productCategory);
        }
    
    
        @Test
        public void findByCategoryTypeInTest(){
            List<Integer>lists= Arrays.asList(1,2,3);
    
            List<ProductCategory> result=productCategoryDao.findByCategoryTypeIn(lists);
            Assert.assertNotEquals(0,result.size());
        }
    
    }
  • com.example.demo目录下创建包名service,并service下创建impl包,接着创建类CategoryService,CategoryServiceImpl
  • package com.example.demo.service;
    
    import com.example.demo.dataobject.ProductCategory;
    
    
    import java.util.List;
    
    public interface CategoryService {
    
        //根据Id查询
        public ProductCategory findOne(Integer caregoryId);
    
        //查询所有
        public List<ProductCategory>findAll();
    
        //根据编号的传入查询所有匹配数据
        public List<ProductCategory> findByCategoryTypeIn(List<Integer> categoryTypeList);
    
        //更新传入数据信息进行更新
        public ProductCategory save(ProductCategory productCategory);
    }
    
  •  
  • package com.example.demo.service.impl;
    
    import com.example.demo.dao.ProductCategoryDao;
    import com.example.demo.dataobject.ProductCategory;
    import com.example.demo.service.CategoryService;
    
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.stereotype.Service;
    
    import java.util.List;
    
    @Service
    public class CategoryServiceImpl implements CategoryService {
    
        @Autowired
        private ProductCategoryDao productCategoryDao;
    
        @Override
        public ProductCategory findOne(Integer caregoryId) {
            return productCategoryDao.findById(caregoryId).get();
        }
    
        @Override
        public List<ProductCategory> findAll() {
            return productCategoryDao.findAll();
        }
    
        @Override
        public List<ProductCategory> findByCategoryTypeIn(List<Integer> categoryTypeList) {
            return productCategoryDao.findByCategoryTypeIn(categoryTypeList);
        }
    
        @Override
        public ProductCategory save(ProductCategory productCategory) {
            return productCategoryDao.save(productCategory);
        }
    }
    
  •  
  •   接着还是要进行必要测试
  • package com.wechat.sell.service.impl;
    
    import com.wechat.sell.dataobject.ProductCategory;
    import org.junit.Assert;
    import org.junit.Test;
    import org.junit.runner.RunWith;
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.boot.test.context.SpringBootTest;
    import org.springframework.test.context.junit4.SpringRunner;
    
    import java.util.ArrayList;
    import java.util.Arrays;
    import java.util.List;
    
    import static org.junit.Assert.*;
    
    
    @RunWith(SpringRunner.class)
    @SpringBootTest
    public class CategoryServiceImplTest {
    
        @Autowired
        private CategoryServiceImpl categoryService;
    
        @Test
        public void findOne() throws Exception{
            ProductCategory productCategory=categoryService.findOne(1);
            System.out.println("productCategory = " + productCategory);
            Assert.assertEquals(1,new Integer(1),productCategory.getCategoryId());
        }
    
        @Test
        public void findAll() throws Exception{
            List<ProductCategory>productCategoryList=categoryService.findAll();
            for(ProductCategory productCategory:productCategoryList){
                System.out.println("================ = " + "================");
                System.out.println("productCategory = " + productCategory);
            }
            Assert.assertNotEquals(0,productCategoryList.size());
        }
    
        @Test
        public void findByCategoryTypeIn() throws Exception{
            List<ProductCategory>productCategoryList=categoryService.findByCategoryTypeIn( Arrays.asList(1,2,3));
            for(ProductCategory productCategory:productCategoryList){
                System.out.println("================ = " + "================");
                System.out.println("productCategory = " + productCategory);
            }
            Assert.assertNotEquals(0,productCategoryList.size());
    
        }
    
        @Test
        public void save() throws Exception{
            ProductCategory productCategory=new ProductCategory();
            productCategory.setCategoryType(2);
            productCategory.setCategoryName("黑科技榜单");
            ProductCategory productCategory1=categoryService.save(productCategory);
            System.out.println("productCategory1 = " + productCategory1);
            Assert.assertNotNull(productCategory1);
        }
    }
  •  

 


博客提供有源码,源码中加入了Logback日志框架,源码可用于项目中套用并自行拓展

源码:源码下载

原创文章,未经允许,请勿盗用

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

SpringBoot框架连接数据库实战(超详细) 的相关文章

随机推荐

  • GDB调试-新手笔记3

    ldd命令 43 readelf ldd 在制作自己的发行版时经常需要判断某条命令需要哪些共享库文件的支持 xff0c 以确保指定的命令在独立的系统内可以可靠的运行 ldd stack0 可以找到stack0程序使用的共享库 xff0c l
  • Spring源码分析(一)Spring的环境搭建与架构

    目录 一 Spring的基本信息1 1 Spring 概述1 2 架构 二 环境搭建2 1 gradle的安装与配置2 2 Spring源码构建 本图 xff1a 川西旅游中拍摄的 xff08 业余摄影 xff09 官网 xff1a Hom
  • RNA-seq:转录组数据分析处理(上)

    RNA seq xff1a 转录组数据分析处理 xff08 上 xff09 目录 RNA seq xff1a 转录组数据分析处理 xff08 上 xff09 一 流程概括二 准备工作1 fastq测序文件2 注释文件和基因组文件的获取 三
  • STM32串口数据接收 --环形缓冲区

    STM32串口数据接收 环形缓冲区 环形缓冲区简介 在单片机中串口通信是我们使用最频繁的 xff0c 使用串口通信就会用到串口的数据接收与发送 xff0c 环形缓冲区方式接收数据可以更好的保证数据丢帧率第 在通信程序中 xff0c 经常使用
  • Linux下驱动开发

    Linux下驱动开发 1 简介 驱动 xff0c 是指驱动计算机里软件的程序 驱动程序全称设备驱动程序 xff0c 是添加到操作系统中的特殊程序 xff0c 其中包含有关硬件设备的信息 驱动程序是操作系统与硬件连接的桥梁 设备驱动最通俗的解
  • openstack单网卡使用多IP说明、openstack虚拟机IP通网关但同网段IP不互通处理方法

    文章目录 openstack虚拟机IP通网关但同网段IP不互通处理方法问题描述处理方法 Openstack中单网卡使用多ip openstack虚拟机IP通网关但同网段IP不互通处理方法 问题描述 云平台的防火墙虚拟机部署再我们云平台上 x
  • Collections.singletonList使用方法

    方法注释 应用 xff1a 这个方法主要用于只有一个元素的优化 xff0c 减少内存分配 xff0c 无需分配额外的内存 xff0c 可以从SingletonList内部类看得出来 由于只有一个element 因此可以做到内存分配最小化 x
  • 如何修改电脑的MAC地址(手把手更改)

    打开控制面板 xff0c 显示如下 xff0c 然后点击 网络和Internet xff08 windows 43 r xff0c 然后输入control xff0c 按下回车 xff0c 即可打开控制面板 xff09 点击完 网络和Int
  • evo的快速安装Ubuntu 18.04

    由于一键安装成功后打开轨迹后报错 xff1a ERROR evo module evo main traj crashed no logfile written disabled 不会解决 xff0c 索性直接用源码安装方式 xff1a 如
  • 基于 SpringBoot + Vue 的音乐网站系统(源代码+数据库+思路文档)

    一 系统介绍 本项目分为管理员与普通用户两种角色 管理员角色包含以下功能 xff1a 后台对用户 歌曲 歌手 歌单信息的管理 用户角色包含以下功能 xff1a 音乐播放用户登录注册用户信息编辑 头像修改歌单打分歌单 歌曲评论歌单列表 歌手列
  • Linux下PS1设置

    PS1简介 PS1命令是linux系统中的一个全局变量 xff0c 用于定义用户命令行的字符显示 学名为 xff1a 默认提示符 盲猜Power Shell 1 PS1变量 span class token comment shell查看变
  • Linux内存管理

    Linux中的程序都是在进程中执行的 xff0c 而每个进程都有自己的虚拟地址空间 xff0c 进程中的内存操作 xff0c 比如访问 xff0c 插入数据都是在这块虚拟地址空间上操作的 虚拟地址空间 虚拟地址空间是一个进程所使用的虚拟内存
  • Maven库打包解决方案:No plugin found for prefix ‘install’ in the current project and in the plgin groups

    问题描述 我的外部本地包 xff0c 需要打包到我的maven库里 然后报错如下 No plugin found for prefix install in the current project and in the plgin grou
  • Ant Design Blazor表格高度自适应

    Ant Design Blazor表格高度自适应 一 先导入js 在 Host cshtml导入js lt component type 61 34 typeof App 34 render mode 61 34 ServerPrerend
  • Gson临时文件被删除造成的stackOverflowError

    错误内容 今天使用Gson序列化的时候出现了stackOverflowError的错误 xff0c 内容如下 xff1a at span class token class name span class token namespace c
  • tcpdump命令参数说明和使用实例、linux解析公网地址会卡顿一下解决方法

    文章目录 tcpdumptcpdump的参数选项基本返回值查看基本用法抓取指定网络接口的所有流量抓取指定网络接口指定主机地址 IP 域名 的所有流量只取出端口 3333 的联机数据包获取指定协议的数据包 如udp 在网口eth1上抓取源端口
  • Linux系统桌面环境(又称图形界面)有哪些?

    Linux系统有许多不同的图形用户界面 xff08 Graphical User Interface xff0c 简称GUI xff09 xff0c 又称桌面环境 以下几乎涵盖了所有的桌面环境 GNOME xff1a GNOME是Linux
  • 艾里斑大小与像元尺寸的匹配问题

    写给自己看的学习记录 xff1a 光具有波粒二象性 xff0c 由此衍生出了几何光学与衍射光学 在光学设计软件中 xff0c 最常用的判断标准是查看点列图的RMS半径以及MTF图的曲线 xff0c 这两者分别代表了两种传播性质的评价方式 在
  • visual studio 和visual studio code 的区别是什么?

    区别有三 xff1a 区别一 xff1a 含义不一样 Visual Studio xff08 简称VS xff09 是美国微软公司的开发工具包系列产品 xff0c 是一个基本完整的开发工具集 xff0c 它包括了整个软件生命周期中所需要的大
  • SpringBoot框架连接数据库实战(超详细)

    SpringBoot框架用于实战 xff08 可直接下载源码进行拓展 xff09 步骤 xff1a 创建数据库mr wen xff0c 新建两条测试数据创建SpringBoot项目编写代码块 xff0c 并进行单元测试 创建数据库mr we