spring-第三章-jdbc
一,回顾
aop:面向切面编程,就是将一些和主业务流程没有关系的公共代码,提取封装到切面类,通过切入点规则,可以对目标方法进行功能增强;也就是可以再目标方法执行的前后添加一段额外逻辑代码;
二,JdbcTemplate模板类
spring框架对数据库的操作在jdbc基础上做了封装,使用spring依赖注入功能,可以吧DataSource(数据源,链接地址,账号,密码,驱动类)注入给JdbcTemplate模板类中,然后就可以使用JdbcTemplate工具类对数据表进行增删改查操作
1、数据库和表
create table userInfo(
id int not null primary key auto_increment,
no char(4) not null unique,
name varchar(20) not null,
pwd varchar(20) not null,
sex int not null,
age int not null
)
insert into userInfo values(0,'U001','小明','123456',1,20);
insert into userInfo values(0,'U002','小红','123456',0,18);
insert into userInfo values(0,'U003','小方','123456',1,21);
2、添加依赖
<!-- spring-context -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>5.1.0.RELEASE</version>
</dependency>
<!-- spring-jdbc -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>5.1.0.RELEASE</version>
</dependency>
<!-- spring-tx -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-tx</artifactId>
<version>5.1.0.RELEASE</version>
</dependency> <dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.18.2</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.47</version>
</dependency>
3、配置数据源DataSource
(1)在src目录中新建jdbc.properties配置文件
jdbc.url=jdbc:mysql://127.0.0.1:3306/spring-test?characterEncoding=utf-8
jdbc.username=root
jdbc.password=123456
(2)在spring.xml中引用资源配置文件
<!-- 引用配置文件 -->
<context:property-placeholder location="classpath:jdbc.properties"/>
(3)在spring.xml中配置数据源以及使用配置文件中的key
<!-- 数据源配置 :配置连接地址、账号、密码;下面的url、username、password属性来自于DriverManagerDataSource的父类AbstractDriverBasedDataSource-->
<bean id="dataSource1" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="url" value="${jdbc.url}"></property>
<property name="username" value="${jdbc.username}"></property>
<property name="password" value="${jdbc.password}"></property>
</bean>
4、注册JdbcTemlate模板工具类
在spring.xml中配置工具类
<!-- 注册jdbcTemplate工具类实例 dataSource属性就是数据源-->
<bean id="jdbcTemplate1" class="org.springframework.jdbc.core.JdbcTemplate">
<property name="dataSource" ref="dataSource1"></property>
</bean>
5、UserInfo实体类
@Data
public class UserInfo {
private Integer id;
private String no;
private String name;
private String pwd;
private Integer sex;
private Integer age;
}
6、UserInfoDao接口
public interface UserInfoDao {
//添加
void add(UserInfo user);
}
7、UserInfoDaoImpl实现类
@Data
public class UserInfoDaoImpl implements UserInfoDao { //工具类
private JdbcTemplate jdbcTemplate; @Override
public void add(UserInfo user) {
//update()可以执行增删改,后面的参数可以可变类型,依次为SQL语句中的?赋值
String sql = "insert into userInfo values(0,?,?,?,?,?)";
jdbcTemplate.update(sql, user.getNo(),user.getName(),user.getPwd(),user.getSex(),user.getAge());
} }
这里的jdbcTemplate属性,必须有set和get方法,否则spring不能正常给它注入实例
8、注册UserInfoDaoImpl实例
在spring.xml中注册
<bean id="userInfoDaoImpl" class="com.yujun.maven.dao.impl.UserInfoDaoImpl">
<property name="jdbcTemplate" ref="jdbcTemplate1"></property>
</bean>
注意的是需要给UserInfoDaoImpl类注入jdbcTemlate的实例
9、添加
public class Demo1 {
public static void main(String[] args) {
//context上下文对象(spring容器)
ApplicationContext context = new ClassPathXmlApplicationContext("spring.xml");
UserInfoDao dao = context.getBean("userInfoDaoImpl", UserInfoDao.class);
UserInfo user = new UserInfo();
user.setAge(20);
user.setName("明明");
user.setNo("U004");
user.setPwd("123456");
user.setSex(0);
dao.add(user);
System.out.println("over...");
}
}
10、修改
(1)UserInfoDao接口中添加方法
//修改
void update(UserInfo user);
(2)UserInfoDaoImpl实现类中重写方法
@Override
public void update(UserInfo user) {
String sql = "update userinfo set no=?,name=?,pwd=?,sex=?,age=? where id=?";
jdbcTemplate.update(sql, user.getNo(),user.getName(),user.getPwd(),user.getSex(),user.getAge(),user.getId());
}
(3)测试
public static void main(String[] args) {
//context上下文对象(spring容器)
ApplicationContext context = new ClassPathXmlApplicationContext("spring.xml");
UserInfoDao dao = context.getBean("userInfoDaoImpl", UserInfoDao.class);
UserInfo user = new UserInfo();
user.setId(5);
user.setAge(22);
user.setName("明明5");
user.setNo("U005");
user.setPwd("654321");
user.setSex(1);
dao.update(user);
System.out.println("over...");
}
11、删除
(1)UserInfoDao接口中添加方法
//删除
void delete(Integer id);
(2)UserInfoDaoImpl实现类中重写方法
@Override
public void delete(Integer id) {
String sql = "delete from userInfo where id=?";
jdbcTemplate.update(sql, id);
}
(3)测试
public static void main(String[] args) {
//context上下文对象(spring容器)
ApplicationContext context = new ClassPathXmlApplicationContext("spring.xml");
UserInfoDao dao = context.getBean("userInfoDaoImpl", UserInfoDao.class);
dao.delete(5);
System.out.println("over...");
}
三、JdbcTemplate模板类-查询
1、查询单个结果
查询userinfo表中的记录数(count(*))
(1)UserInfoDao接口添加方法
//查询count(*)
int queryCount();
(2)UserInfoDaoImpl实现类重写方法
@Override
public int queryCount() {
String sql = "select count(*) from userInfo";
Integer count = jdbcTemplate.queryForObject(sql, int.class);
return count;
}
(3)测试
public static void main(String[] args) {
//context上下文对象(spring容器)
ApplicationContext context = new ClassPathXmlApplicationContext("spring.xml");
UserInfoDao dao = context.getBean("userInfoDaoImpl", UserInfoDao.class);
int count = dao.queryCount();
System.out.println("总记录数:"+count);
System.out.println("over...");
}
2、查询单一实体对象
根据用户的ID查询出唯一的用户实体数据
(1)UserInfoDao接口添加方法
//根据ID查询唯一数据
UserInfo queryById(Integer id);
(2)UserInfoDaoImpl实现类重写方法
@Override
public UserInfo queryById(Integer id) {
String sql = "select * from userInfo where id=?";
return jdbcTemplate.queryForObject(sql, new RowMapper<UserInfo>() {
//RowMapper是行映射器,需要再mapRow()方法中对每行数据进行映射
@Override
public UserInfo mapRow(ResultSet rs, int rowNum) throws SQLException {
String no = rs.getString("no");
String name = rs.getString("name");
String pwd = rs.getString("pwd");
Integer sex = rs.getInt("sex");
Integer age = rs.getInt("age");
UserInfo user = new UserInfo(id, no, name, pwd, sex, age);
return user;
}
}, id);
}
(3)测试
public static void main(String[] args) {
//context上下文对象(spring容器)
ApplicationContext context = new ClassPathXmlApplicationContext("spring.xml");
UserInfoDao dao = context.getBean("userInfoDaoImpl", UserInfoDao.class);
UserInfo info = dao.queryById(1);
System.out.println(info);
System.out.println("over...");
}
3、查询集合对象
(1)UserInfoDao接口添加方法
//根据sex查询数据集合
List<UserInfo> queryBySex(int sex);
(2)UserInfoDaoImpl实现类重写方法
@Override
public List<UserInfo> queryBySex(int sex) {
String sql = "select * from userInfo where sex=?";
return jdbcTemplate.query(sql, new RowMapper<UserInfo>() {
//RowMapper是行映射器,需要再mapRow()方法中对每行数据进行映射
@Override
public UserInfo mapRow(ResultSet rs, int rowNum) throws SQLException {
int id = rs.getInt("id");
String no = rs.getString("no");
String name = rs.getString("name");
String pwd = rs.getString("pwd");
Integer sex = rs.getInt("sex");
Integer age = rs.getInt("age");
UserInfo user = new UserInfo(id, no, name, pwd, sex, age);
return user;
}
}, sex);
}
这里的映射器写法和前面查询单一实体对象一样
(3)测试
public static void main(String[] args) {
//context上下文对象(spring容器)
ApplicationContext context = new ClassPathXmlApplicationContext("spring.xml");
UserInfoDao dao = context.getBean("userInfoDaoImpl", UserInfoDao.class);
List<UserInfo> list = dao.queryBySex(0);
list.forEach(System.out::println);
System.out.println("over...");
}
四、补充说明
上面我们使用JdbcTemplate模板工具类完成后简单的增删改查操作,更多详细的操作可以查看官方文档或百度;
在上面的案例中,有2个问题需要被完善:
(1) 数据源没有使用连接池技术
(2) 数据源没有事务的支持
关于上述两个问题,我们会在下次课spring+hibernate中一起完善;
spring-第三章-jdbc的更多相关文章
- spring第三章
第三章 实现AOP AOP:面向方面编程,AOP能够使您将所有模块共有的特性与应用程序的主要业务逻辑隔离开 一.AOP介绍 横切关注点:在Web应用程序中,有一些服务(如登录.安全和事务管理)不是应用 ...
- spring boot 笔记--第三章
spring boot 笔记 第三章,使用Spring boot 构建系统: 强烈建议支持依赖管理的构建系统,Maven或Gradle 依赖管理: Spring Boot的每版本都会提供它支持的依赖列 ...
- 一起来学Spring Cloud | 第三章:服务消费者 (负载均衡Ribbon)
一.负载均衡的简介: 负载均衡是高可用架构的一个关键组件,主要用来提高性能和可用性,通过负载均衡将流量分发到多个服务器,多服务器能够消除单个服务器的故障,减轻单个服务器的访问压力. 1.服务端负载均衡 ...
- Spring 学习指南 第三章 bean的配置 (未完结)
第三章 bean 的配置 在本章中,我们将介绍以下内容: bean 定义的继承: 如何解决 bean 类的构造函数的参数: 如何配置原始类型 (如 int .float 等) .集合类型(如 ja ...
- 《精通Spring4.x企业应用开发实战》第三章
这一章节主要介绍SpringBoot的使用,也是学习的重点内容,之后就打算用SpringBoot来写后台,所以提前看一下还是很有必要的. 3.SpringBoot概况 3.1.1SpringBoot发 ...
- Spring第三天
Spring第三天 整体课程安排(3天+2天): 第一天:Spring框架入门.IoC控制反转的配置管理.Spring Web集成.Spring Junit集成. 第二天:Spring AOP面向切面 ...
- 第六章 JDBC
第一章 JDBC 一.JDBC的简介 1.什么是JDBC JDBC是java数据库连接(java database connectivity)技术的简称,它充当了java应用程序与各个不同数据库之间进 ...
- 第三章Hibernate关联映射
第三章Hibernate关联映射 一.关联关系 类与类之间最普通的关系就是关联关系,而且关联是有方向的. 以部门和员工为列,一个部门下有多个员工,而一个员工只能属于一个部门,从员工到部门就是多对一关联 ...
- 一起来学Spring Cloud | 第二章:服务注册和发现组件 (Eureka)
本篇文章,很浅显的一步步讲解如何搭建一个能运行的springcloud项目(带所有操作截图).相信!看完本篇之后,你会觉得springcloud搭建如此简单~~~~ 一. Eureka简介: 1.1 ...
随机推荐
- Azure Front Door(三)启用 Web Application Firewall (WAF) 保护Web 应用程序,拒绝恶意攻击
一,引言 上一篇我们利用 Azure Front Door 为后端 VM 部署提供流量的负载均衡.因为是演示实例,也没有实际的后端实例代码,只有一个 "Index.html" 的静 ...
- ES 终于可以搜到”悟空哥“了!
Elasticsearch 搜索引擎内置了很多种分词器,但是对中文分词不友好,所以我们需要借助第三方中文分词工具包. 悟空哥专门研究了下 ik 中文分词工具包该怎么玩,希望对大家有所帮助. 本文主要内 ...
- [图论]最优布线问题:prim
最优布线问题 目录 最优布线问题 Description Input Output Sample Input Sample Output Hint 解析 代码 Description 学校有n台计算机 ...
- KubeEdge EdgeMesh设计原理
EdgeMesh主要用来做边缘侧微服务的互访. ServiceMesh service mesh是一个服务网格的概念.在传统的架构里面都是通过像Dubbo来进行服务治理,服务治理的程序和我们应用程序强 ...
- MySQL提升笔记(2):存储引擎盘点
在前面我们了解了server层调用存储引擎层接口来完成sql的执行,使用存储引擎的好处是:每个存储引擎都有各自的特点,能够根据具体的应用建立不同存储引擎表. 需要注意的是,存储引擎是基于表的,而不是数 ...
- 通过Dapr实现一个简单的基于.net的微服务电商系统(五)——一步一步教你如何撸Dapr之状态管理
状态管理和上一章的订阅发布都算是Dapr相较于其他服务网格框架来讲提供的比较特异性的内容,今天我们来讲讲状态管理. 目录:一.通过Dapr实现一个简单的基于.net的微服务电商系统 二.通过Dapr实 ...
- Spring Boot demo系列(一):Hello World
2021.2.24 更新 1 新建工程 打开IDEA选择新建工程并选择Spring Initializer: 可以在Project JDK处选择JDK版本,下一步是选择包名,语言,构建工具以及打包工具 ...
- Java 8 Optional
这是一个可以为null的容器对象.如果值存在则isPresent()方法会返回true,调用get()方法会返回该对象. package com.polaris; import java.util.A ...
- 机器人走方格-51nod解题
M * N的方格,一个机器人从左上走到右下,只能向右或向下走. 有多少种不同的走法? 注意:给定 M, N 是一个正整数. 示例 输入: 1行, 2个数M,N,中间用空格隔开.(2 <= m,n ...
- 深入学习Android系统上mount命令的使用
博客链接:http://blog.csdn.net/qq1084283172/article/details/52493227 在Android系统的预装apk病毒和elf病毒的清除时,经常需要先获取 ...