04.SpringBoot 整合Druid+Mybatis-Plus实现数据持久化

前言

数据持久化就是将内存中的数据模型转为存储模型,以及将存储模型转换为内存中的数据模型的模型。存储模型可以是关系模型、xml、二进制流等。本文实现的是对象模型到关系模型之间的转换。

1、数据连接池

数据库连接是一种关键的有限的昂贵的资源,同时建立过多的数据库链接得不到及时释放则容易导致系统内存溢出至崩溃。数据库连接池是在应用程序启动时建立足够的数据库连接,将这些连接放到一个“池”中,当连接申请超过池中的数量时则在请求队列中等待。连接池技术尽可能地重用了小号内存地资源,大大节省了内存,提高服务器的效率。
JAVA主流的数据库连接有C30P、DBCP、Druid、HikariCP。本文介绍Springboot +Druid的整合,下面是实现步骤

1.1、添加Druid的maven依赖

<!-- druid -->
<dependency>
     <groupId>com.alibaba</groupId>
     <artifactId>druid-spring-boot-starter</artifactId>
     <version>1.1.17</version>
 </dependency>

 <!--mysql driver -->
 <dependency>
     <groupId>mysql</groupId>
     <artifactId>mysql-connector-java</artifactId>
     <version>8.0.20</version>
     <scope>runtime</scope>
 </dependency>

1.2、添加配置文件(application.yml)

spring:
  datasource:
    #MySQL
    driver-class-name: com.mysql.cj.jdbc.Driver #数据库连接驱动
    url: jdbc:mysql://localhost:3306/kljf-boot?useUnicode=true&characterEncoding=UTF-8&serverTimezone=Asia/Shanghai 
    username: renren
    password: 123456
    type: com.alibaba.druid.pool.DruidDataSource
    druid:
      web-stat-filter:
        enabled: true
        url-pattern: "/*"
        exclusions: "*.js,*.gif,*.jpg,*.png,*.css,*.iso"
      stat-view-servlet: #设置访问druid监控页的账号和密码,默认没有
        login-username: admin
        login-password: 123456
        url-pattern: "/druid/*"
        allow: 127.0.0.1 # 只允许127.0.0.1访问druid的监控页
        reset-enable: false
        enabled: true
      use-global-data-source-stat: true #合并多个DruidDataSource的监控数据
      filters: stat,wall,slf4j # 配置扩展插件
      connection-properties: druid.stat.mergeSql=true;druid.stat.slowSqlMillis=500 #通过connectProperties属性来打开mergeSql功能;慢SQL记录

1.3 在浏览器方位127.0.0.1/druid/,可看到druid的登录框

2、Mybatis-Plus

2.1、简介

MyBatis-Plus(简称 MP)是一个 MyBatis 的增强工具,在 MyBatis 的基础上只做增强不做改变,为简化开发、提高效率而生。

2.2、添加依赖

<dependency>
    <groupId>org.projectlombok</groupId>
    <artifactId>lombok</artifactId>
    <optional>true</optional>
</dependency>
<dependency>
    <groupId>com.baomidou</groupId>
    <artifactId>mybatis-plus-boot-starter</artifactId>
    <version>3.4.1</version>
</dependency>

2.3、分页的实现

package io.kljf.boot.config.handler;

import com.baomidou.mybatisplus.annotation.DbType;
import com.baomidou.mybatisplus.extension.plugins.MybatisPlusInterceptor;
import com.baomidou.mybatisplus.extension.plugins.PaginationInterceptor;
import com.baomidou.mybatisplus.extension.plugins.inner.PaginationInnerInterceptor;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.annotation.Order;

/**
 * @author katherine
 * @version 2020-11-16
 **/
@Configuration
public class MyBatisPlusConfig {

    @Bean
    @Order(0)
    public MybatisPlusInterceptor mybatisPlusInterceptor(){
        MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();
        interceptor.addInnerInterceptor(new PaginationInnerInterceptor(DbType.MYSQL));
        return interceptor;
    }

}

2.4、CRUD实现

2.4.1、创建数据库表
CREATE TABLE `sys_user`  (
  `id` varchar(60) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL COMMENT 'id',
  `username` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL COMMENT '用户名',
  PRIMARY KEY (`id`) USING BTREE,
  UNIQUE INDEX `username`(`username`) USING BTREE COMMENT '用户名唯一索引'
) ENGINE = InnoDB CHARACTER SET = utf8 COLLATE = utf8_general_ci ROW_FORMAT = Dynamic;

SET FOREIGN_KEY_CHECKS = 1;
2.4.2、创建实体类
package io.kljf.boot.modules.sys.entity;

import com.baomidou.mybatisplus.annotation.*;
import lombok.Data;

import java.util.Date;

/**
 * @author katherine
 * @version 2020-11-13
 **/
@Data
@TableName("sys_user")
public class UserEntity {

    /**
     * 用户ID
     */
    @TableId(type= IdType.ASSIGN_UUID)
    private String id;
     /**
     * 用户名
     */
    private String username;

    /**
     * 创建时间
     */
    private Date createTime;
    /**
     * 修改时间
     */
    private Date updateTime;
}

@TableName 表名注解,详见Mybatis-Plus 官网
@TableId 主键注解 详见Mybatis-Plus 官网

2.4.3、创建Mapper
package io.kljf.boot.modules.sys.dao;

import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import io.kljf.boot.modules.sys.entity.UserEntity;
import org.apache.ibatis.annotations.Mapper;

@Mapper
public interface UserDao  extends BaseMapper<UserEntity> {

}

2.4.4、创建Service接口

package io.kljf.boot.modules.sys.services;

import com.baomidou.mybatisplus.extension.service.IService;
import io.kljf.boot.modules.sys.entity.UserEntity;

/**
 * @author katherine
 * @version 2020-11-13
 **/
public interface IUserService extends IService<UserEntity> {

}

2.4.5、实现Service接口

package io.kljf.boot.modules.sys.services.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import io.kljf.boot.modules.sys.dao.UserDao;
import io.kljf.boot.modules.sys.entity.UserEntity;
import io.kljf.boot.modules.sys.services.IUserService;
import org.springframework.stereotype.Service;

/**
 * @author katherine
 * @version 2020-11-13
 **/
@Service
public class UserServiceImpl extends ServiceImpl<UserDao,UserEntity> implements IUserService {
}

2.4.5、写单元测试

package io.kljf.boot;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.kljf.boot.modules.sys.controller.UserControllerTest;
import io.kljf.boot.modules.sys.entity.UserEntity;
import io.kljf.boot.modules.sys.services.IUserService;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;

import java.util.List;

/**
 * @author katherine
 * @version 2020-11-13
 **/
@RunWith(SpringRunner.class)
@SpringBootTest(classes = KljfApplication.class)
public class TestMyBatisPlus {
    private static Logger logger = LoggerFactory.getLogger(TestMyBatisPlus.class);
    @Autowired
    IUserService userService;

    @Test
    public void test(){
        // 模拟新增一百条数据
        for(int i =0;i<100;i++){
            UserEntity userEntity = new UserEntity();
            userEntity.setUsername("username"+i);
            userService.save(userEntity);
        }
        // 模拟获取全部数据
        List<UserEntity> userlist = userService.list();
        userlist = userService.list();
        logger.info(userlist.toString());
        // 模拟获取用户名包含10的数据
        userlist = userService.list(new QueryWrapper<UserEntity>().like("username","10"));
        logger.info(userlist.toString());
        // 根据获取ID修改数据
        UserEntity userNew = new UserEntity();
        userNew.setId("0075f0dd0d327254424db2bd7c7ffc5e");
        userNew.setUsername("小超人");
        userService.updateById(userNew);
        // 根据ID获取数据
        UserEntity userEntity = userService.getById("0075f0dd0d327254424db2bd7c7ffc5e");
        logger.info(userEntity.toString());
        // 获取分页
        IPage<UserEntity> page = new Page<>();
        IPage<UserEntity> userIPage = userService.page(page);
        logger.info(userIPage.toString());

    }
}

[编辑本段]Turbo C2.0    介绍      Turbo C2.0不仅是一个快捷、高效的编译程序,同时还有一个易学、易用的集成开发环境。使用Turbo C2.0无需独立地编辑、编译和连接程序,就能建立并运行C语言程序。因为这些功能都组合在Turbo 2.0的集成开发环境内,并且可以通过一个简单的主屏幕使用这些功能。    基本配置要求   Turbo C 2.0可运行于IBM-PC系列微机,包括XT,AT及IBM 兼容机。此时要求DOS2.0或更高版本支持,并至少需要448K的RAM,可在任何彩、单色80列监视器上运行。支持数学协处理器芯片,也可进行浮点仿真,这将加快程序的执行。 [编辑本段]Turbo C 2.0的主要文件的简单介绍   INSTALL.EXE 安装程序文件   TC.EXE 集成编译   TCINST.EXE 集成开发环境的配置设置程序   TCHELP.TCH 帮助文件   THELP.COM 读取TCHELP.TCH的驻留程序README 关于Turbo C的信息文件   TCCONFIG.EXE 配置文件转换程序MAKE.EXE   项目管理工具TCC.EXE   命令行编译TLINK.EXE   Turbo C系列连接器TLIB.EXE   Turbo C系列库管理工具C0?.OBJ 不   同模式启动代码C?.LIB   不同模式运行库GRAPHICS.LIB   图形库EMU.LIB   8087仿真库FP87.LIB 8087库   *.H Turbo C头文件   *.BGI 不同显示器图形驱动程序   *.C Turbo C例行程序(源文件)   其中:上面的?分别为:T Tiny(微型模式)S Small(小模式)C Compact(紧凑模式)M Medium(中型模式)L Large(大模式)H Huge(巨大模式)    Turbo C++ 3.0   “Turbo C++ 3.0”软件是Borland公司在1992年推出的强大的——C语言程序设计与C++面向对象程序设计 的集成开发工具。它只需要修改一个设置选项,就能够在同一个IDE集成开发环境下设计和编译以标准 C 和 C++ 语法设计的程序文件。 [编辑本段]C 语言   C语言起始于1968年发表的CPL语言,它的许多重要思想都来自于Martin Richards在1969年研制的BCPL语言,以及以BCPL语言为基础的与Ken Thompson在1970年研制的B语言。Ken Thompson用B语言写了第一个UNIX操作系统。M.M.Ritchie1972年在B语言的基础上研制了C语言,并用C语言写成了第一个在PDP-11计算机上研制的UNIX操作系统。1977年出现了独立于极其的C语言编译文本《看移植C语言编译程序》,从而大大简化了把C语言编译程序移植到新环境中所做的工作,这本身也就使UNIX的日益广泛使用,C语言也迅速得到推广。   1983年美国国家标准化协会(ANSI)根据C语言问世以来的各种版本,对C语言的发展和扩充制定了新的标准,成为ANSI C。1987年ANSI又公布了新标准————87ANSI C。   目前在微型计算机上使用的有Microsoft C、Quick C、Turbo C等多种版本。这些不同的C语言版本,基本部分是相同的,但是在有关规定上有略有差异。   C 语言发展如此迅速, 而且成为最受欢迎的语言之一, 主要因为它具有强大的功能。许多著名的系统软件, 如DBASE Ⅲ PLUS、DBASE Ⅳ 都是由C 语言编写的。用C 语言加上一些汇编语言子程序, 就更能显示C 语言的优势了,象PC- DOS ,WORDSTAR等就是用这种方法编写的。归纳起来C 语言具有下列特点:   1. C是中级语言   它把高级语言的基本结构和语句与低级语言的实用性结合起来。C 语言可以象汇编语言一样对位、字节和地址进行操作, 而这三者是计算机最基本的工作单元。   2. C是结构式语言   结构式语言的显著特点是代码及数据的分隔化, 即程序的各个部分除了必要的信息交流外彼此独立。这种结构化方式可使程序层次清晰, 便于使用、维护以及调试。C 语言是以函数形式提供给用户的, 这些函数可方便的调用, 并具有多种循环、条件语句控制程序流向, 从而使程序完全结构化。   3. C语言功能齐全   C 语言具有各种各样的数据类型, 并引入了指针概念, 可使程序效率更高。另外C 语言也具有强大的图形功能, 支持多种显示器和驱动器。而且计算功能、逻辑判断功能也比较强大, 可以实现决策目的。   4. C语言适用范围大   C 语言还有一个突出的优点就是适合于多种操作系统, 如DOS、UNIX,也适用于多种机型。   C语言的优点很多,但是也存在一些缺点,如运算优先级太多,运算能力方面不像其它高级语言那样强,语法定义不严格等。但是这些都不能阻止C语言成为一门广受欢迎的计算机编程语言
Turbo C2.0 介绍   Turbo C2.0不仅是一个快捷、高效的编译程序,同时还有一个易学、易用的集成开发环境。使用Turbo C2.0无需独立地编辑、编译和连接程序,就能建立并运行C语言程序。因为这些功能都组合在Turbo 2.0的集成开发环境内,并且可以通过一个简单的主屏幕使用这些功能。 基本配置要求   Turbo C 2.0可运行于IBM-PC系列微机,包括XT,AT及IBM 兼容机。此时要求DOS2.0或更高版本支持,并至少需要448K的RAM,可在任何彩、单色80列监视器上运行。支持数学协处理器芯片,也可进行浮点仿真,这将加快程序的执行。 主要文件的简单介绍   INSTALL.EXE 安装程序文件   TC.EXE 集成编译   TCINST.EXE 集成开发环境的配置设置程序   TCHELP.TCH 帮助文件   THELP.COM 读取TCHELP.TCH的驻留程序README 关于Turbo C的信息文件   TCCONFIG.EXE 配置文件转换程序MAKE.EXE   项目管理工具TCC.EXE   命令行编译TLINK.EXE   Turbo C系列连接器TLIB.EXE   Turbo C系列库管理工具C0?.OBJ 不   同模式启动代码C?.LIB   不同模式运行库GRAPHICS.LIB   图形库EMU.LIB   8087仿真库FP87.LIB 8087库   *.H Turbo C头文件   *.BGI 不同显示器图形驱动程序   *.C Turbo C例行程序(源文件)   其中:上面的?分别为:T Tiny(微型模式)S Small(小模式)C Compact(紧凑模式)M Medium(中型模式)L Large(大模式)H Huge(巨大模式)
### 回答1: 在 TURBO C 2.0 中,您可以使用 biosdisk() 函数来格式化软盘。 下面是一段代码示例: ``` #include <stdio.h> #include <dos.h> int main() { // 定义扇区的大小 unsigned int sector_size[3] = {512, 512, 1024}; // 定义填充字节 unsigned char fill_char[3] = {0xF6, 0xF6, 0x48}; // 格式化磁道 700 的前三个扇区 for (int i = 0; i < 3; i++) { int result = biosdisk(2, 0, 70, 0, i + 1, 1, sector_size[i], fill_char[i]); if (result != 0) { printf("格式化扇区 %d 失败,返回码: %d\n", i + 1, result); } } return 0; } ``` 请注意,在使用 biosdisk() 函数之前,需要包含 dos.h 头文件。 希望这能帮到您! ### 回答2使用TURBO C 2.0语言,可以通过以下代码格式化软盘的70磁道0面,并分别格式化3个扇区,大小分别为512字节、512字节和1024字节。其中,前两个扇区使用F6填充,第三个扇区使用48填充。 ```c #include<stdlib.h> #include<stdio.h> #include<dos.h> void formatFloppyDisk(){ union REGS regs; regs.h.ah = 0x0;// To format a floppy disk, we set AH=0 regs.h.dl = 0;// Drive number (0=A, 1=B, etc.) regs.x.cx = 0;// Track number to format regs.h.dh = 0;// Head number regs.h.al = 0;// Sector size (0=default, 1=512 bytes, 2=1024 bytes, 3=2048 bytes etc.) int FILL_BYTE = 0;// The byte value to fill the sectors with during formatting int NUM_SECTORS = 3;// Number of sectors to format // To format 70th track 0th head regs.x.ax = 0x1301; // 0x13 = Reset disk system, 01H = Reset only specified drive int86(0x13, &regs, &regs); // BIOS interrupt to reset disk system for (int i=0; i<NUM_SECTORS; i++){ regs.x.ax = 0x3101; // 0x31 = Write Format, 01H = Format only current track regs.x.bx = 0x0001; // 0x00 = Drive A:, 01H = Head 1, 0 = Generate ID Field depending on the disk in the drive 1 = Keep the ID Field all zeros regs.x.cx = 0x0170; // Track number=70(0-79 range) regs.h.dh = 0x00; // Head number=0 or 1 regs.h.al = 0x02; // Control byte=always zero regs.x.dx = i+1; // Sector number starting from 1 regs.x.si = 0x0000; // segment and offset of read/write buffer regs.x.di = 0x0000; // segment and offset of result if(i == 2){ FILL_BYTE = 0x48; // Fill the third sector with 48 regs.x.ax = 0x3102; // 0x31 = Write Format, 02H = Format sequential tracks immediately following the one being formatted }else{ FILL_BYTE = 0xF6; // Fill the first two sectors with F6 } regs.h.ah = FILL_BYTE; // Fill the sector with specified byte int86(0x13, &regs, &regs); // BIOS interrupt to format the specified sector } } int main(){ formatFloppyDisk(); return 0; } ``` 上述代码使用了INT 0x13,即BIOS中断服务例程,来执行软盘格式化操作。通过设置寄存器的不同参数,可以指定要格式化的磁道、面、扇区大小和填充字节。在这个例子中,我们格式化了软盘70磁道0面的3个扇区,前两个扇区使用F6填充,第三个扇区使用48填充。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值