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.properties
和 user.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运行却又在普通渲染管线之外的程序,通过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作用是能够去查看原码, 新版本idea默认移除了这个按钮😢 那么让我们来把它找出来叭✋ 但是我们可以通过设置,使用step into就可以进入系统方法。 1.单击…...
【2024秋招】用友后端BIP部门hr面-2023.8.31
反思 首先,我想为你提供一个背景:HR面试不仅仅是为了了解你的背景和经验,还包括你的性格、沟通能力、问题解决技巧、团队合作精神和其他软性技能。基于你提供的信息,我会提供一些可能影响offer级别的点: 答案的质量&a…...

[ Windows ] ping IP + Port 测试 ip 和 端口是否通畅
开发过程中经常会黑窗口中手动测试一下计划请求的目标ip和端口是否通畅,测试方式如下: 一、单纯测试ip是否能够 ping 通,这个比较熟悉了,运行 cmd 打开黑窗口 输入如下指令,能够如下提示信息,表示端口是通…...
Golang协程的概念、用法、场景及案例
在当今的软件开发领域中,高性能和并发性是很重要的。开发人员需要编写能够有效利用多核处理器的程序,以提高应用程序的性能和响应能力。Go语言(Golang)就是一种在这方面非常强大的编程语言,它提供了一种称为协程&#…...

Redis 主从复制,哨兵,集群——(3)集群篇
目录 1. 前篇回顾 2. Redis 集群是什么? 3. Redis 集群的优点 4. Redis 集群的槽位概念 5. 什么是分片? 6. 如何找到给定key的分片? 7. 分片槽位的设计有什么好处? 8. key映射到节点的三种解决方案 8.1 哈希取余分区 8.…...
Flink之Watermark水印、水位线
Watermark水印、水位线 水位线概述水印本质生成WatermarkWatermark策略WatermarkStrategy工具类使用Watermark策略 内置Watermark生成器单调递增时间戳分配器固定延迟的时间戳分配器 自定义WatermarkGenerator周期性Watermark生成器标记Watermark生成器Watermark策略与Kafka连接…...

uni-app:对数组对象进行以具体某一项的分类处理
一、原始数据 这里定义为五个数组,种类product有aaa,bbb两种 原始数据在data中进行定义 res: {"success": true,"devices": [{no: 0,product: aaa,alias: "设备1",assign: [["a1", "a2", "a3"],[&q…...

顺序队列----数据结构
队列的概念 队列,符合先进先出特点的一种数据结构,是一种特殊的线性表,但它不像线性表一样可以任意插入和删除操作,而是只允许在表的一端插入,也就是在队列的尾部进行插入;只允许在表的另一端进行删除&…...
【Python学习笔记】字符串格式化
1. printf 风格 这种格式化语法 和 传统的C语言printf函数 一样 。 salary input(请输入薪资:)# 计算出缴税额,存入变量tax tax int(salary) *25/100 # 计算出税后工资,存入变量aftertax aftertax int(salary) *75/100 print(税前薪资&…...

RIP,EIGRP,OSPF区别
1. 动态路由协议的作用是什么? 2. 路由协议都有哪些种类? 3. 如何判断路由协议的优劣? -- RIP,EIGRP,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系统,要求接上type-c 进行dp输出显示以后,dp端和主板端都有声音。rk原有系统默认是接上dp显示以后,主板的喇叭声音会被切掉,导致没有声音。要让喇叭和dp同时输出声音需要做如下修改: --- a/…...

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

SystemVerilog Assertions应用指南 Chapter1.29“ disable iff构造
在某些设计情况中,如果一些条件为真,则我们不想执行检验。换句话说,这就像是一个异步的复位,使得检验在当前时刻不工作。SVA提供了关键词“ disable iff来实现这种检验器的异步复位。“ disable iff”的基本语法如下。 disable iff (expression) <property definition> …...
C++设计模式之MVC
MVC(Model-View-Controller)是一种经典的软件架构模式,用于组织和分离应用程序的不同部分,以提高代码的可维护性、可扩展性和重用性。MVC模式将应用程序分为三个主要组成部分: Model(模型)&…...
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 启…...

UE5 学习系列(二)用户操作界面及介绍
这篇博客是 UE5 学习系列博客的第二篇,在第一篇的基础上展开这篇内容。博客参考的 B 站视频资料和第一篇的链接如下: 【Note】:如果你已经完成安装等操作,可以只执行第一篇博客中 2. 新建一个空白游戏项目 章节操作,重…...

7.4.分块查找
一.分块查找的算法思想: 1.实例: 以上述图片的顺序表为例, 该顺序表的数据元素从整体来看是乱序的,但如果把这些数据元素分成一块一块的小区间, 第一个区间[0,1]索引上的数据元素都是小于等于10的, 第二…...

如何将联系人从 iPhone 转移到 Android
从 iPhone 换到 Android 手机时,你可能需要保留重要的数据,例如通讯录。好在,将通讯录从 iPhone 转移到 Android 手机非常简单,你可以从本文中学习 6 种可靠的方法,确保随时保持连接,不错过任何信息。 第 1…...
uniapp中使用aixos 报错
问题: 在uniapp中使用aixos,运行后报如下错误: AxiosError: There is no suitable adapter to dispatch the request since : - adapter xhr is not supported by the environment - adapter http is not available in the build 解决方案&…...
根据万维钢·精英日课6的内容,使用AI(2025)可以参考以下方法:
根据万维钢精英日课6的内容,使用AI(2025)可以参考以下方法: 四个洞见 模型已经比人聪明:以ChatGPT o3为代表的AI非常强大,能运用高级理论解释道理、引用最新学术论文,生成对顶尖科学家都有用的…...

学习STC51单片机32(芯片为STC89C52RCRC)OLED显示屏2
每日一言 今天的每一份坚持,都是在为未来积攒底气。 案例:OLED显示一个A 这边观察到一个点,怎么雪花了就是都是乱七八糟的占满了屏幕。。 解释 : 如果代码里信号切换太快(比如 SDA 刚变,SCL 立刻变&#…...

HarmonyOS运动开发:如何用mpchart绘制运动配速图表
##鸿蒙核心技术##运动开发##Sensor Service Kit(传感器服务)# 前言 在运动类应用中,运动数据的可视化是提升用户体验的重要环节。通过直观的图表展示运动过程中的关键数据,如配速、距离、卡路里消耗等,用户可以更清晰…...

SiFli 52把Imagie图片,Font字体资源放在指定位置,编译成指定img.bin和font.bin的问题
分区配置 (ptab.json) img 属性介绍: img 属性指定分区存放的 image 名称,指定的 image 名称必须是当前工程生成的 binary 。 如果 binary 有多个文件,则以 proj_name:binary_name 格式指定文件名, proj_name 为工程 名&…...
Vite中定义@软链接
在webpack中可以直接通过符号表示src路径,但是vite中默认不可以。 如何实现: vite中提供了resolve.alias:通过别名在指向一个具体的路径 在vite.config.js中 import { join } from pathexport default defineConfig({plugins: [vue()],//…...
django blank 与 null的区别
1.blank blank控制表单验证时是否允许字段为空 2.null null控制数据库层面是否为空 但是,要注意以下几点: Django的表单验证与null无关:null参数控制的是数据库层面字段是否可以为NULL,而blank参数控制的是Django表单验证时字…...