当前位置: 首页 > news >正文

spring的简单使用(配合Druid操作数据库)

文章目录

  • 准备数据
  • `pom.xml`文件中引用需要的库
  • 准备好dao层接口和service层接口和实现类
  • 准备好 `jdbc.properties` 和 `user.properties`
  • 编写Druid的jdbcConfig配置类
  • 编写spring的配置类`SpringConfig`
  • 编写Dao层的实现类的逻辑
  • 测试类
  • 参考文献

准备数据

create database if not exists db_spring;
use db_spring;
drop table if exists tb_user;
create table if not exists tb_user
(id      int primary key auto_increment,name    varchar(10) not null unique,age     int,id_card varchar(10)
);insert into tb_user(name, age, id_card)values ('张三', 23, '10001'),('李四', 18, '10002'),('王五', 34, '10003'),('赵六', 45, '10004');select * from tb_user;

pom.xml文件中引用需要的库

<dependencies><dependency><groupId>org.springframework</groupId><artifactId>spring-context</artifactId><version>6.0.12</version></dependency><dependency><groupId>com.alibaba</groupId><artifactId>druid</artifactId><version>1.1.10</version></dependency><dependency><groupId>com.mysql</groupId><artifactId>mysql-connector-j</artifactId><version>8.0.33</version></dependency>
</dependencies>

准备好dao层接口和service层接口和实现类

  • dao层
    // 接口
    package com.test.dao;public interface UserDao {void selectAll();void selectById();
    }
    
  • service层
    // 接口
    package com.test.service;public interface UserService {void selectAll();void selectById();
    }// 实现类
    package com.test.service.impl;import com.test.dao.UserDao;
    import com.test.service.UserService;
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.stereotype.Service;/*** Service注解就是标识这个类是service层的bean,spring启动的时候,就会把它放入到Ioc容器中* 跟这个相似还有 @Repository 和 @Controller*/
    @Service
    public class UserServiceImpl implements UserService {// Autowired注解是自动装配@Autowiredprivate UserDao userDao;@Overridepublic void selectAll() {userDao.selectAll();}@Overridepublic void selectById() {userDao.selectById();}
    }
    

准备好 jdbc.propertiesuser.properties

这里分开写,是为了练习加载多个配置文件,所以需要再resources资源文件中新建这两个配置文件

  • jdbc.properties
    jdbc.driver=com.mysql.cj.jdbc.Driver
    jdbc.url=jdbc:mysql:///db_spring?useServerPrepStmts=true
    jdbc.username=root
    jdbc.password=root1234
    
  • user.properties
    name=张三
    age=23
    sex=男
    idCard=10001
    id=2
    

编写Druid的jdbcConfig配置类

public class JdbcConfig {/*** 这里通过Value注解从properties配置文件中读取数据* 这里的前提,就是在 SpringConfig这个配置类中* 通过PropertySource注解引用的资源文件中的配置文件*/@Value("${jdbc.driver}")private String driver;@Value("${jdbc.url}")private String url;@Value("${jdbc.username}")private String username;@Value("${jdbc.password}")private String password;/*** 通过 注解Bean来加载第三方*/@Beanpublic DataSource dataSource() {DruidDataSource ds = new DruidDataSource();ds.setDriverClassName(driver);ds.setUrl(url);ds.setUsername(username);ds.setPassword(password);return ds;}
}

编写spring的配置类SpringConfig

package com.test.config;import org.springframework.context.annotation.*;/*** Configuration注解:设置当前类为配置类* ComponentScan注解:用于扫描指定路径重点bean对象* PropertySource注解:用于把指定的配置文件加载借来* Import注解:是用于导入三方的bean类进入Ioc容器*/
@Configuration
@ComponentScan({"com.test.dao", "com.test.service"})
@PropertySource({"classpath:user.properties", "classpath:jdbc.properties"})
@Import(JdbcConfig.class)
public class SpringConfig {
}

编写Dao层的实现类的逻辑

// Repository:表示是dao层的bean
@Repository("userDao")
public class UserDaoImpl implements UserDao {// 自动装配@Autowiredprivate DataSource dataSource;// 获取配置文件中的数据@Value("${id}")private int id;@Overridepublic void selectAll() {try {// 操作数据库Connection connection = dataSource.getConnection();String sql = "select * from tb_user";PreparedStatement prepareStatement = connection.prepareStatement(sql);ResultSet resultSet = prepareStatement.executeQuery();while (resultSet.next()) {int id = resultSet.getInt("id");String name = resultSet.getString("name");String idCard = resultSet.getString("id_card");int age = resultSet.getInt("age");System.out.println("id:" + id + " , name:" + name + " , age:" + age + " , idCard:" + idCard);}// 释放资源resultSet.close();prepareStatement.close();connection.close();} catch (Exception e) {e.printStackTrace();}}@Overridepublic void selectById() {try {Connection connection = dataSource.getConnection();String sql = "select * from tb_user where id = ?";PreparedStatement prepareStatement = connection.prepareStatement(sql);prepareStatement.setInt(1, id);ResultSet resultSet = prepareStatement.executeQuery();while (resultSet.next()) {int id = resultSet.getInt("id");String name = resultSet.getString("name");String idCard = resultSet.getString("id_card");int age = resultSet.getInt("age");System.out.println("id:" + id + " , name:" + name + " , age:" + age + " , idCard:" + idCard);}// 释放资源resultSet.close();prepareStatement.close();connection.close();} catch (Exception e) {e.printStackTrace();}}
}

测试类

public class Main {public static void main(String[] args) {/*** 获取Ioc容器* 这里是通过SpringConfig这个配置类来获取*/ApplicationContext ctx = new AnnotationConfigApplicationContext(SpringConfig.class);// 获取beanUserService userService = ctx.getBean(UserService.class);userService.selectAll();System.out.println("====== selectById ======");userService.selectById();}
}

参考文献

1. 黑马程序员SSM框架教程

相关文章:

spring的简单使用(配合Druid操作数据库)

文章目录 准备数据pom.xml文件中引用需要的库准备好dao层接口和service层接口和实现类准备好 jdbc.properties 和 user.properties编写Druid的jdbcConfig配置类编写spring的配置类SpringConfig编写Dao层的实现类的逻辑测试类参考文献 准备数据 create database if not exists …...

10.20作业

#include “widget.h” #include “ui_widget.h” Widget::Widget(QWidget *parent) QWidget(parent) , ui(new Ui::Widget) { ui->setupUi(this); t new QTimer(this); connect(t, &QTimer::timeout, this, &Widget::timeout_Slot); ui->text->setPlacehold…...

笔记1 Compute Shaders

Wending 2022/10/29 15:43:54 Compute Shaders是在GPU运行却又在普通渲染管线之外的程序&#xff0c;通过Compute Shader我们可以将大量可以并行的计算放到GPU中计算从而节省CPU资源 Wending 2022/10/29 15:44:27 反正不是传统的shader 不常用 博毅创为Blake老师 2022/10/29 15…...

IntelliJ IDEA 2023版本 Debug 时没有Force Step Into 按钮解决方法

IntelliJ IDEA 2023版本 Debug 时没有Force Step Into 按钮解决方法 force step into作用是能够去查看原码&#xff0c; 新版本idea默认移除了这个按钮&#x1f622; 那么让我们来把它找出来叭✋ 但是我们可以通过设置&#xff0c;使用step into就可以进入系统方法。 1.单击…...

【2024秋招】用友后端BIP部门hr面-2023.8.31

反思 首先&#xff0c;我想为你提供一个背景&#xff1a;HR面试不仅仅是为了了解你的背景和经验&#xff0c;还包括你的性格、沟通能力、问题解决技巧、团队合作精神和其他软性技能。基于你提供的信息&#xff0c;我会提供一些可能影响offer级别的点&#xff1a; 答案的质量&a…...

[ Windows ] ping IP + Port 测试 ip 和 端口是否通畅

开发过程中经常会黑窗口中手动测试一下计划请求的目标ip和端口是否通畅&#xff0c;测试方式如下&#xff1a; 一、单纯测试ip是否能够 ping 通&#xff0c;这个比较熟悉了&#xff0c;运行 cmd 打开黑窗口 输入如下指令&#xff0c;能够如下提示信息&#xff0c;表示端口是通…...

Golang协程的概念、用法、场景及案例

在当今的软件开发领域中&#xff0c;高性能和并发性是很重要的。开发人员需要编写能够有效利用多核处理器的程序&#xff0c;以提高应用程序的性能和响应能力。Go语言&#xff08;Golang&#xff09;就是一种在这方面非常强大的编程语言&#xff0c;它提供了一种称为协程&#…...

Redis 主从复制,哨兵,集群——(3)集群篇

目录 1. 前篇回顾 2. Redis 集群是什么&#xff1f; 3. Redis 集群的优点 4. Redis 集群的槽位概念 5. 什么是分片&#xff1f; 6. 如何找到给定key的分片&#xff1f; 7. 分片槽位的设计有什么好处&#xff1f; 8. key映射到节点的三种解决方案 8.1 哈希取余分区 8.…...

Flink之Watermark水印、水位线

Watermark水印、水位线 水位线概述水印本质生成WatermarkWatermark策略WatermarkStrategy工具类使用Watermark策略 内置Watermark生成器单调递增时间戳分配器固定延迟的时间戳分配器 自定义WatermarkGenerator周期性Watermark生成器标记Watermark生成器Watermark策略与Kafka连接…...

uni-app:对数组对象进行以具体某一项的分类处理

一、原始数据 这里定义为五个数组&#xff0c;种类product有aaa,bbb两种 原始数据在data中进行定义 res: {"success": true,"devices": [{no: 0,product: aaa,alias: "设备1",assign: [["a1", "a2", "a3"],[&q…...

顺序队列----数据结构

队列的概念 队列&#xff0c;符合先进先出特点的一种数据结构&#xff0c;是一种特殊的线性表&#xff0c;但它不像线性表一样可以任意插入和删除操作&#xff0c;而是只允许在表的一端插入&#xff0c;也就是在队列的尾部进行插入&#xff1b;只允许在表的另一端进行删除&…...

【Python学习笔记】字符串格式化

1. printf 风格 这种格式化语法 和 传统的C语言printf函数 一样 。 salary input(请输入薪资&#xff1a;)# 计算出缴税额&#xff0c;存入变量tax tax int(salary) *25/100 # 计算出税后工资&#xff0c;存入变量aftertax aftertax int(salary) *75/100 print(税前薪资&…...

RIP,EIGRP,OSPF区别

1. 动态路由协议的作用是什么&#xff1f; 2. 路由协议都有哪些种类&#xff1f; 3. 如何判断路由协议的优劣&#xff1f; -- RIP&#xff0c;EIGRP&#xff0c;OSPF - 动态路由协议 -- 路由协议 - 路由器上的软件 -- 帮助路由器彼此之间同步路由表 -- 相互的传递…...

驱动day2作业

编写应用程序控制三盏灯亮灭 head.h #ifndef __HEAD_H__ #define __HEAD_H__ #define PHY_LED1_MODER 0x50006000 #define PHY_LED2_MODER 0x50007000 #define PHY_LED1_ODR 0x50006014 #define PHY_LED2_ODR 0x50007014 #define PHY_RCC 0x50000A28#endif demo1.c #includ…...

MySQL基本操作之创建数据表

设计表: 学生表(Student): 学号(StudentID)- 主键,用于唯一标识每个学生姓名(Name)性别(Gender)年龄(Age)出生日期(BirthDate)地址(Address)电话(Phone)邮箱(Email)课程表(Course): 课程号(CourseID)- 主键,用于唯一标识每门课程课程名(CourseNam…...

rk平台android12修改dp和喇叭同时输出声音

客户的rk3588主板android12系统&#xff0c;要求接上type-c 进行dp输出显示以后&#xff0c;dp端和主板端都有声音。rk原有系统默认是接上dp显示以后&#xff0c;主板的喇叭声音会被切掉&#xff0c;导致没有声音。要让喇叭和dp同时输出声音需要做如下修改&#xff1a; --- a/…...

经典网络模型

Alexnet VGG VGG的启示 VGGNet采用了多次堆叠3x3的卷积核&#xff0c;这样做的目的是减少参数的数量。 例如&#xff0c;2个3x3的卷积核效果相当于1个5x5的卷积核效果&#xff0c;因为它们的感受野&#xff08;输入图像上映射区域的大小&#xff09;相同。但2个3x3卷积核的参数…...

SystemVerilog Assertions应用指南 Chapter1.29“ disable iff构造

在某些设计情况中,如果一些条件为真,则我们不想执行检验。换句话说,这就像是一个异步的复位,使得检验在当前时刻不工作。SVA提供了关键词“ disable iff来实现这种检验器的异步复位。“ disable iff”的基本语法如下。 disable iff (expression) <property definition> …...

C++设计模式之MVC

MVC&#xff08;Model-View-Controller&#xff09;是一种经典的软件架构模式&#xff0c;用于组织和分离应用程序的不同部分&#xff0c;以提高代码的可维护性、可扩展性和重用性。MVC模式将应用程序分为三个主要组成部分&#xff1a; Model&#xff08;模型&#xff09;&…...

Windows 下Tomcat监测重启

echo off setlocal enabledelayedexpansion rem 链接 set URL"localhost:8080/XXX.jsp" rem tomcat目录 set TOMCAT_HOMED:\apache-tomcat-7.0.100-windows-x64\apache-tomcat-7.0.100 rem 关闭tomcat命令的路径 set CLOSE_CMD%TOMCAT_HOME%\bin\shutdown.bat rem 启…...

多模态AI图像编辑工具对比:Nano Banana与Qwen实战解析

1. 项目概述&#xff1a;多模态图像编辑工具对比实战最近在测试两款前沿的图像编辑工具——Nano Banana&#xff08;基于Gemini 2.5 Flash的图像处理方案&#xff09;和Qwen Image Edit时&#xff0c;发现它们在27种典型场景下的表现差异远超预期。作为长期跟踪多模态AI发展的从…...

Flutter 3.10+ 实战:用NavigationRail快速搞定桌面端/大屏App的侧边导航栏

Flutter 3.10 桌面端开发&#xff1a;用NavigationRail构建专业级侧边导航系统 当Flutter应用从手机屏幕扩展到桌面或平板大屏时&#xff0c;传统的底部导航栏(BottomNavigationBar)往往显得捉襟见肘。在Windows/macOS或iPad等大屏设备上&#xff0c;侧边导航不仅更符合用户习惯…...

【AI】cursor使用场景示例

基于 Cursor 官方文档及高赞社区实践按 8 个高频开发场景 给出可直接复制粘贴的 Prompt 模板。每个模板遵循官方推荐的 6 段式结构&#xff08;Goal → Context → Constraints → Examples → Output → Verify&#xff09;&#xff0c;并内嵌 上下文引用语法。一、新功能开发…...

Spring Security配置踩坑大全:从CSRF禁用、密码加密到自定义登录页,一次讲清

Spring Security实战避坑指南&#xff1a;CSRF、密码加密与登录页定制深度解析 1. 当POST请求遭遇403&#xff1a;CSRF防护的精准控制策略 那个令人抓狂的403错误页面&#xff0c;可能是大多数开发者首次接触Spring Security时最深刻的记忆。明明在Postman测试正常的API接口&…...

DiP框架:像素空间扩散模型的高效图像生成技术

1. DiP框架&#xff1a;像素空间扩散模型的技术突破在计算机视觉领域&#xff0c;扩散模型已经成为图像生成的新标杆&#xff0c;但其计算效率与生成质量之间的矛盾始终是制约其广泛应用的关键瓶颈。传统潜在扩散模型(LDMs)通过VAE压缩图像到潜在空间确实降低了计算负担&#x…...

MCP插件生态搭建全链路拆解,覆盖协议注册、能力协商、上下文同步与热重载调试

更多请点击&#xff1a; https://intelliparadigm.com 第一章&#xff1a;MCP插件生态搭建全景概览 MCP&#xff08;Model Control Protocol&#xff09;作为新一代模型交互协议&#xff0c;其插件生态是实现大模型能力可扩展、可编排与可治理的核心基础设施。插件并非孤立模块…...

数字考古:MS-DOS源代码中的三重时空对话

数字考古&#xff1a;MS-DOS源代码中的三重时空对话 【免费下载链接】MS-DOS The original sources of MS-DOS 1.25, 2.0, and 4.0 for reference purposes 项目地址: https://gitcode.com/GitHub_Trending/ms/MS-DOS 在计算机历史的尘埃中&#xff0c;MS-DOS的源代码如…...

深入NVDLA的“心脏”:拆解卷积引擎的四种工作模式与选型策略

深入NVDLA的“心脏”&#xff1a;拆解卷积引擎的四种工作模式与选型策略 在深度学习推理加速领域&#xff0c;NVDLA&#xff08;NVIDIA深度学习加速器&#xff09;凭借其模块化设计和可配置特性&#xff0c;成为众多边缘计算场景的首选方案。作为算法优化工程师&#xff0c;我们…...

终极静音方案:5步掌握FanControl免费风扇控制软件

终极静音方案&#xff1a;5步掌握FanControl免费风扇控制软件 【免费下载链接】FanControl.Releases This is the release repository for Fan Control, a highly customizable fan controlling software for Windows. 项目地址: https://gitcode.com/GitHub_Trending/fa/Fan…...

虚拟文件系统 GVfs

GVfs&#xff08;GNOME Virtual File System&#xff09; 是 GNOME 桌面环境的用户空间虚拟文件系统&#xff0c;基于 GIO&#xff08;GLib 的 I/O 抽象库&#xff09;实现&#xff0c;用于统一访问本地、网络与设备存储&#xff0c;替代旧版 GnomeVFS。GVfs 以 D-Bus 为总线、…...