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 启…...
css实现圆环展示百分比,根据值动态展示所占比例
代码如下 <view class""><view class"circle-chart"><view v-if"!!num" class"pie-item" :style"{background: conic-gradient(var(--one-color) 0%,#E9E6F1 ${num}%),}"></view><view v-else …...
DeepSeek 赋能智慧能源:微电网优化调度的智能革新路径
目录 一、智慧能源微电网优化调度概述1.1 智慧能源微电网概念1.2 优化调度的重要性1.3 目前面临的挑战 二、DeepSeek 技术探秘2.1 DeepSeek 技术原理2.2 DeepSeek 独特优势2.3 DeepSeek 在 AI 领域地位 三、DeepSeek 在微电网优化调度中的应用剖析3.1 数据处理与分析3.2 预测与…...
(二)TensorRT-LLM | 模型导出(v0.20.0rc3)
0. 概述 上一节 对安装和使用有个基本介绍。根据这个 issue 的描述,后续 TensorRT-LLM 团队可能更专注于更新和维护 pytorch backend。但 tensorrt backend 作为先前一直开发的工作,其中包含了大量可以学习的地方。本文主要看看它导出模型的部分&#x…...
UDP(Echoserver)
网络命令 Ping 命令 检测网络是否连通 使用方法: ping -c 次数 网址ping -c 3 www.baidu.comnetstat 命令 netstat 是一个用来查看网络状态的重要工具. 语法:netstat [选项] 功能:查看网络状态 常用选项: n 拒绝显示别名&#…...
对WWDC 2025 Keynote 内容的预测
借助我们以往对苹果公司发展路径的深入研究经验,以及大语言模型的分析能力,我们系统梳理了多年来苹果 WWDC 主题演讲的规律。在 WWDC 2025 即将揭幕之际,我们让 ChatGPT 对今年的 Keynote 内容进行了一个初步预测,聊作存档。等到明…...
Cinnamon修改面板小工具图标
Cinnamon开始菜单-CSDN博客 设置模块都是做好的,比GNOME简单得多! 在 applet.js 里增加 const Settings imports.ui.settings;this.settings new Settings.AppletSettings(this, HTYMenusonichy, instance_id); this.settings.bind(menu-icon, menu…...
镜像里切换为普通用户
如果你登录远程虚拟机默认就是 root 用户,但你不希望用 root 权限运行 ns-3(这是对的,ns3 工具会拒绝 root),你可以按以下方法创建一个 非 root 用户账号 并切换到它运行 ns-3。 一次性解决方案:创建非 roo…...
MODBUS TCP转CANopen 技术赋能高效协同作业
在现代工业自动化领域,MODBUS TCP和CANopen两种通讯协议因其稳定性和高效性被广泛应用于各种设备和系统中。而随着科技的不断进步,这两种通讯协议也正在被逐步融合,形成了一种新型的通讯方式——开疆智能MODBUS TCP转CANopen网关KJ-TCPC-CANP…...
k8s业务程序联调工具-KtConnect
概述 原理 工具作用是建立了一个从本地到集群的单向VPN,根据VPN原理,打通两个内网必然需要借助一个公共中继节点,ktconnect工具巧妙的利用k8s原生的portforward能力,简化了建立连接的过程,apiserver间接起到了中继节…...
html-<abbr> 缩写或首字母缩略词
定义与作用 <abbr> 标签用于表示缩写或首字母缩略词,它可以帮助用户更好地理解缩写的含义,尤其是对于那些不熟悉该缩写的用户。 title 属性的内容提供了缩写的详细说明。当用户将鼠标悬停在缩写上时,会显示一个提示框。 示例&#x…...
