标签:Jdbc.Druid.Mybatis.Plus;

一、简介

项目工程中,集成数据库实现对数据的增晒改查管理,是最基础的能力,而对于这个功能的实现,其组件选型也非常丰富;

通过如下几个组件来实现数据库的整合;

Druid连接池:阿里开源的数据库连接池,并且提供SQL执行的监控能力;

MybatisPlus框架:基于Mybatis框架的增强工具包,可以用于简化持久层开发,显著的提高效率;

MySQL数据库:常用的关系型数据库组件,在案例中使用Druid组件来连接数据库;

二、工程搭建

1、工程结构

2、依赖管理

Druid连接池使用的是1.2.18版本;在mybatis-plus组件中依赖mybatis框架的3.5.10版本;MySQL本地环境是5.7版本,这里依赖包使用8.0.19版本;

<!-- MySql数据库 -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>${mysql.version}</version>
</dependency>
<!-- Druid组件 -->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid-spring-boot-3-starter</artifactId>
<version>${druid-spring-boot.version}</version>
</dependency>
<!-- JDBC依赖 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-jdbc</artifactId>
<version>${spring-boot.version}</version>
</dependency>
<!-- MybatisPlus组件 -->
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-boot-starter</artifactId>
<version>${mybatis-plus.version}</version>
</dependency>

三、Druid连接池

1、配置文件

有关于Druid连接池的可配置参数还有很多,可以参考源码中的描述或者官方案例,此处只提供部分常见的参数配置;

spring:
datasource:
type: com.alibaba.druid.pool.DruidDataSource
druid:
# 数据库
url: jdbc:mysql://localhost:3306/boot-jdbc
username: root
password: 123456
driver-class-name: com.mysql.cj.jdbc.Driver
# 连接池-初始化大小
initial-size: 10
# 连接池-最大连接数
max-active: 100
# 最大等待时间
max-wait: 60000
# 连接池-最小空闲数
min-idle: 10
# 检测空闲连接
test-while-idle: true
# 最小空闲时间
min-evictable-idle-time-millis: 300000

1.2 配置类

配置两个Bean对象,分别DruidDataSource类和JdbcTemplate类;

@Configuration
public class DruidConfig { @Bean("dataSource")
@ConfigurationProperties(prefix = "spring.datasource.druid")
public DruidDataSource dataSource() {
return new DruidDataSource();
} @Bean("jdbcTemplate")
public JdbcTemplate jdbcTemplate() {
return new JdbcTemplate(dataSource());
}
}

四、JDBC操作

1、数据库表

boot-jdbc数据库中添加两张测试表,用户基础信息tb_user表和用户扩展信息tb_user_extd表,脚本文件在工程的resources/sql-script目录下;

CREATE TABLE `tb_user` (
`id` int(11) NOT NULL AUTO_INCREMENT COMMENT '主键ID',
`user_name` varchar(30) NOT NULL COMMENT '用户名称',
`email` varchar(50) DEFAULT NULL COMMENT '邮件',
`phone` varchar(20) NOT NULL COMMENT '手机号',
`create_time` datetime DEFAULT NULL COMMENT '创建时间',
`update_time` datetime DEFAULT NULL COMMENT '更新时间',
`state` int(1) DEFAULT '1' COMMENT '状态:1启用,2删除',
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COMMENT='用户基础信息'; CREATE TABLE `tb_user_extd` (
`id` int(11) NOT NULL AUTO_INCREMENT COMMENT '主键ID',
`user_id` int(11) NOT NULL COMMENT '用户ID',
`city_name` varchar(50) DEFAULT NULL COMMENT '城市名称',
`school` varchar(200) DEFAULT NULL COMMENT '学校名称',
PRIMARY KEY (`id`),
KEY `user_id_index` (`user_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COMMENT='用户扩展信息';

2、JdbcTemplate

JdbcTemplate是由spring-jdbc组件提供,支持DataSource的注册,是对数据库操作的深层封装,支持一系列数据操作方法;

@Service
public class JdbcService { private static final Logger logger = LoggerFactory.getLogger(JdbcService.class);
@Resource
private JdbcTemplate jdbcTemplate ; /**
* 添加数据
*/
public int addData (User user){
return jdbcTemplate.update(
"INSERT INTO `tb_user` (`user_name`, `email`, `phone`, `create_time`, `update_time`) VALUES (?, ?, ?, ?, ?)",
user.getUserName(),user.getEmail(),user.getPhone(),user.getCreateTime(),user.getUpdateTime());
}
/**
* 查询全部
*/
public List<User> queryAll (){
return jdbcTemplate.query("SELECT * FROM tb_user WHERE state=1",new BeanPropertyRowMapper<>(User.class));
}
/**
* 修改字段
*/
public int updateName (Integer id,String name){
return jdbcTemplate.update("UPDATE `tb_user` SET `user_name` = ? WHERE `id` = ?",name,id);
}
/**
* 主键删除
*/
public int deleteId (Integer id){
return jdbcTemplate.update("DELETE FROM `tb_user` WHERE `id` = ?",id);
}
}

五、MybatisPlus框架

1、配置管理

1.1 配置类

在配置类中,添加MapperScan注解用来扫描和注册MyBatis框架的mapper接口,以及设置PaginationInnerInterceptor分页拦截器;

@Configuration
@MapperScan("com.boot.jdbc.mapper")
public class MybatisConfig { /**
* 分页
*/
@Bean
public MybatisPlusInterceptor paginationInterceptor() {
MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();
interceptor.addInnerInterceptor(new PaginationInnerInterceptor(DbType.MYSQL));
return interceptor;
}
}

1.2 配置文件

在日志中输出mybatis框架解析的SQL语句,方便在测试的时候快速发现问题;

mybatis-plus:
configuration:
log-impl: org.apache.ibatis.logging.stdout.StdOutImpl

2、Mapper

Mapper接口编写数据库操作方法,Mapper.xml文件中定义数据库执行的SQL语句,在mybatis-plus组件中提供很多单表操作的默认方法实现,也可以自定义方法;

2.1 Mapper接口

public interface UserMapper extends BaseMapper<User> {

    /**
* 自定义分页
*/
IPage<UserModel> queryUserPage(@Param("page") IPage<User> page);
}

2.2 Mapper文件

<mapper namespace="com.boot.jdbc.mapper.UserMapper">
<select id="queryUserPage" resultType="com.boot.jdbc.entity.UserModel">
SELECT
tb1.id userId,
tb1.user_name userName,
tb1.email,
tb1.phone,
tb1.create_time createTime,
tb1.update_time updateTime,
tb1.state,
tb2.school,
tb2.city_name cityName
FROM tb_user tb1
LEFT JOIN tb_user_extd tb2 ON tb1.id = tb2.user_id
WHERE tb1.state='1'
ORDER BY tb1.id DESC
</select>
</mapper>

3、单元测试

编写UserMapper接口测试,很多默认实现的方法参考BaseMapper接口即可,或者参考IService接口和ServiceImpl实现类,提供了更加丰富的扩展方法;

public class UserMapperTest {

    @Resource
private UserMapper userMapper ; @Test
public void testInsert (){
List<User> userBatch = Arrays.asList(
new User(null,"Zhang三","Zhang@qq.com","18623459687",new Date(),new Date(),1));
userBatch.forEach(userMapper::insert);
} @Test
public void testUpdate (){
User user = userMapper.selectById(1);
user.setState(2);
userMapper.updateById(user);
} @Test
public void testDelete (){
userMapper.deleteById(7);
} @Test
public void testQuery (){
List<User> userColumnsList = new LambdaQueryChainWrapper<>(userMapper)
.select(User::getUserName,User::getPhone,User::getEmail)
.like(User::getPhone,"189").orderByDesc(User::getId).last("limit 2").list();
userColumnsList.forEach(System.out::println);
} @Test
public void testPage (){
// 1、默认分页查询
IPage<User> userPage = new Page<>(2,2) ;
IPage<User> userPageList = userMapper.selectPage(userPage,new QueryWrapper<>());
userPageList.getRecords().forEach(System.out::println); // 2、自定义查询分页
IPage<UserModel> userModelPage = userMapper.queryUserPage(userPage);
userModelPage.getRecords().forEach(System.out::println);
}
}

六、参考源码

文档仓库:
https://gitee.com/cicadasmile/butte-java-note 源码仓库:
https://gitee.com/cicadasmile/butte-spring-parent

SpringBoot3数据库集成的更多相关文章

  1. [转]Django与遗留系统和数据库集成

    From:http://www.czug.org/python/django/17.html 尽管Django最适合从零开始开发项目--所谓的"绿色领域"开发--将框架与遗留系统和 ...

  2. 将mysql数据库集成到idea中

    将mysql数据库集成到idea中

  3. [ABP教程]第七章 作者:数据库集成

    Web开发教程7 作者:数据库集成 关于此教程 在这个教程系列中,你将要构建一个基于ABP框架的应用程序 Acme.BookStore.这个应用程序被用于甘丽图书页面机器作者.它将用以下开发技术: E ...

  4. SpringBoot3.x原生镜像-Native Image尝鲜

    前提 Spring团队致力于为Spring应用程序提供原生映像支持已经有一段时间了.在SpringBoo2.x的Spring Native实验项目中酝酿了3年多之后,随着Spring Framewor ...

  5. SpringBoot3正式版将于11月24日发布:都有哪些新特性?

    从 2018 年 2 月 28 号发布 Spring Boot 2.0 版本开始,整个 2.X 版本已经经过了 4 年多的时间,累计发布了 95 个不同的版本,而就在前不久,2.X 系列的也已经迎来了 ...

  6. 这可能是最全的SpringBoot3新版本变化了!

    11月24号,Spring Boot 3.0 发布了第一个正式的 GA 版本,一起看看新版本到底有哪些变化. 2.7版本升级指南 官方提供了一个从 2.7 版本升级到 3.0 的指南:https:// ...

  7. SpringBoot3.x中spring.factories功能被移除的解决方案

    背景 笔者所在项目组在搭建一个全新项目的时候选用了SpringBoot3.x,项目中应用了很多SpringBoot2.x时代相关的第三方组件例如baomidou出品的mybatis-plus.dyna ...

  8. SpringBoot3.0 + SpringSecurity6.0+JWT

    JWT_SpringSecurity SpringBoot3.0 + SpringSecurity6.0+JWT Spring Security 是 Spring 家族中的一个安全管理框架. 一般We ...

  9. Springboot3整合使用ja-captcha行为验证码解决方案

    截止到目前,Springboot最新稳定版本已经迭代到3.0.5,而我们项目中使用的行为验证码框架ja-captcha还没有适配Springboot3,码云上类似的请求也没有得到过回应,于是决定自己动 ...

  10. Qt数据库集成应用封装

    平时的大大小小的项目中,基本上都需要与数据库打交道,会遇到各种各样的应用场景,本人主要遇到四种场景1:数据库自动重连,例如mysql数据库中经常遇到服务器挂掉的情况,需要自动检测并重新连接数据库.2: ...

随机推荐

  1. 2022-04-12:给定一个字符串形式的数,比如“3421“或者“-8731“, 如果这个数不在-32768~32767范围上,那么返回“NODATA“, 如果这个数在-32768~32767范围上

    2022-04-12:给定一个字符串形式的数,比如"3421"或者"-8731", 如果这个数不在-32768~32767范围上,那么返回"NODAT ...

  2. 2021-05-19:给定一个非负数组成的数组,长度一定大于1,想知道数组中哪两个数&的结果最大。返回这个最大结果。时间复杂度O(N),额外空间复杂度O(1)。

    2021-05-19:给定一个非负数组成的数组,长度一定大于1,想知道数组中哪两个数&的结果最大.返回这个最大结果.时间复杂度O(N),额外空间复杂度O(1). 福大大 答案2021-05-1 ...

  3. promise及异步编程async await

    前置说明 ECMAScript 6 新增了正式的 Promise(期约)引用类型,支持优雅地定义和组织异步逻辑.接下来几个版本增加了使用 async 和 await 关键字定义异步函数的机制 Java ...

  4. vue全家桶进阶之路42:Vue3 SCSS、SASS、CSS

    SCSS和SASS都是CSS预处理器,它们的主要目的是简化CSS的编写,增加可维护性,并提供更丰富的功能.下面是它们与普通的CSS的区别: 语法:SCSS和SASS都具有比普通CSS更丰富的语法.其中 ...

  5. AssertionError: Expected a `Response`, `HttpResponse` or `HttpStreamingResponse` to be returned from

    函数里面return response问题: 1.没有 2.写错 3.位置错 例如: return Response('确认成功')

  6. 【Vue2.x源码系列08】Diff算法原理

    什么是虚拟DOM DOM是很慢的,其元素非常庞大,当我们频繁的去做 DOM更新,会产生一定的性能问题,我们可以直观感受一下 div元素包含的海量属性 在Javascript对象中,虚拟DOM 表现为一 ...

  7. Cesium中监听MOUSE_MOVE事件获取经纬度和高度

    有时候在这个圆球上获取精确的经度纬度还不容易,特别是高度 还好在cesium提供了接口,看 let selft = this; const scene = this.viewer.scene; var ...

  8. 【python基础】编写/运行hello world项目

    1.编写hello world项目 编程界每种语言的第一个程序往往都是输出hello world.因此我们来看看,如何用Python输出hello world. 1.如果你是初学者,main.py中的 ...

  9. dockder 学习第一篇

    1 docker安装 1 yum包的更新到最新 yum update 2 安装需要软件包,yum-util [root@localhost ~]# yum install -y yum-utils d ...

  10. RT_object

    以下图片来自"张世争"的微博