Spring 框架下的 JDBC
Spring JDBC
Spring 对JDBC技术规范做了进一步封装,它又叫Spring JDBCTemplate(jdbc模板技术)
纯JDBC:代码清晰的、效率最高、代码是最烦的、
Spring JDBCTemplate:代码相对来说就不那么清晰,效率要低一点,代码相对简单
如何进行Spring和jdbc的集合?(数据库的连接池)
(1) 导入jar 包:spring-jdbc.jar 驱动类 连接池 DruidUtil2(框架的原型)
(2) 配置类:@Configuration
(3) @Spring IOC + JDBC 实现
JdbcConfig: a.配置属性 b.配置DataSource Bean
(4) 配置JdbcTemplate Bean @Bean
1.pom.xml 所需要的jar包
<!-- https://mvnrepository.com/artifact/org.springframework/spring-jdbc -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>${spring.version}</version>
</dependency>
<!-- MySQL数据库连接池 -->
<!-- https://mvnrepository.com/artifact/mysql/mysql-connector-java -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.48</version>
</dependency>
<!-- Druid -->
<!-- https://mvnrepository.com/artifact/com.alibaba/druid -->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>1.1.20</version>
</dependency>
2. 一个实体类:Account.java
public class Account {
private int id;
private String name;
private Double balance;
public Account( String name, Double balance) {
super();
this.name = name;
this.balance = balance;
}
public Account(int id, String name, Double balance) {
super();
this.id = id;
this.name = name;
this.balance = balance;
}
public Account() {
super();
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Double getBalance() {
return balance;
}
public void setBalance(Double balance) {
this.balance = balance;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((balance == null) ? 0 : balance.hashCode());
result = prime * result + id;
result = prime * result + ((name == null) ? 0 : name.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Account other = (Account) obj;
if (balance == null) {
if (other.balance != null)
return false;
} else if (!balance.equals(other.balance))
return false;
if (id != other.id)
return false;
if (name == null) {
if (other.name != null)
return false;
} else if (!name.equals(other.name))
return false;
return true;
}
@Override
public String toString() {
return "Account [id=" + id + ", name=" + name + ", balance=" + balance + "]";
}
}
3. 接口:IAccount.java
import java.util.List; /**
* AccountDao接口
* @author 张泽
*/
public interface IAccountDao {
List<Account> findAll();
void delete(Account act);
void saveOrUpdate(Account act);
}
4.1 接口实现类(JDBC):AccountDaoJdbcImpl.java
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List; import javax.sql.DataSource; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
//@Component
@Repository("accountDaoJdbcImpl") //-- 存储、仓库/ 做存储服务
public class AccountDaoJdbcImpl implements IAccountDao {
@Autowired
private DataSource ds; @Override
public List<Account> findAll() {
try {
Connection con = ds.getConnection();
String sql = "select * from account";
Statement stmt = con.createStatement();
ResultSet rs = stmt.executeQuery(sql);
List<Account> acts = new ArrayList<>();
while(rs.next()) {
Account act = new Account(rs.getInt(1),rs.getString(2),rs.getDouble(3));
acts.add(act);
}
return acts; } catch (Exception e) {e.printStackTrace();} return null;
} @Override
public void delete(Account act) {
// TODO Auto-generated method stub } @Override
public void saveOrUpdate(Account act) {
// TODO Auto-generated method stub } }
4.2 接口实现类(Spring JDBCTemplate):AccountDaoTemplateImpl.java
import java.util.List; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Repository; @Repository("accountDaoTemplateImpl")
public class AccountDaoTemplateImpl implements IAccountDao {
@Autowired
private JdbcTemplate jdbcTemplate; @Override
public List<Account> findAll() {
System.out.println("accountDaoTemplateImpl");
return jdbcTemplate.query(
"select * from account",
new BeanPropertyRowMapper<Account>(Account.class)
);
} @Override
public void saveOrUpdate(Account act) { if(act.getId()==0) {
jdbcTemplate.update(
"insert into account(name,balance) values(?,?)",
new Object[] {act.getName(),act.getBalance()}
);
}else {
jdbcTemplate.update(
"update account set name=?,balance=? where id=?",
new Object[] {act.getName(),act.getBalance(),act.getId()}
);
} } @Override
public void delete(Account act) {
jdbcTemplate.update(
"delete from account where id=?",
new Object[] {act.getId()}
);
} }
5.1 JDBC 配置资源:jdbc.properties
jdbc.driverClass=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/demo
jdbc.username=root
jdbc.password=root pool.maxActive=10
5.2 JDBC 配置类:JdbcConfig.java
import javax.sql.DataSource; import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import org.springframework.jdbc.core.JdbcTemplate; import com.alibaba.druid.pool.DruidDataSource; /**
* JdbcConfig类
* @author 张泽
*
*/
@Configuration
@PropertySource("classpath:jdbc.properties")
//--你的配置信息的位置
public class JdbcConfig {
//-- 1. 获取配置信息
@Value("${jdbc.driverClass}")
private String driver;
@Value("${jdbc.url}")
private String url;
@Value("${jdbc.username}")
private String username;
@Value("${jdbc.password}")
private String password; @Value("${pool.maxActive}")
private int maxActive; //-- 2. 数据库连接池对象
@Bean(name="dataSource")
public DataSource createDataSource() {
DruidDataSource ds = new DruidDataSource();
ds.setDriverClassName(driver);
ds.setUrl(url);
ds.setUsername(username);
ds.setPassword(password);
ds.setMaxActive(maxActive); return ds;
} //-- 3. 配置JdbcTemplate
@Bean(name="jdbcTemplate")
public JdbcTemplate createJdbcTemplate(DataSource ds) {
return new JdbcTemplate(ds);//-- 利用数据源构造JdbcTemplate
} }
6. Spring 配置类:SpringConfig.java
/**
* Spring 配置类
* 多配置的使用方式
*/
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import; @Configuration
@ComponentScan("day")//--所在包名
@Import(JdbcConfig.class) //-- 在主配置中导入子配置
public class SpringConfig { }
7. 主函数入口:Invoker.java
import javax.sql.DataSource; import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext; public class Invoker {
public static void main(String[] args) {
ApplicationContext ctx=
new AnnotationConfigApplicationContext(SpringConfig.class);
DataSource ds = (DataSource)ctx.getBean("dataSource");
System.out.println(ds);
}
}
8. 测试类:TestAccountDao.java
import java.util.List; import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; @RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes= {SpringConfig.class})
public class TestAccountDao {
@Autowired
@Qualifier("accountDaoTemplateImpl")//-- 选择要调用 接口的实现类
private IAccountDao actDao; @Test
public void testFind() {
List<Account> acts = actDao.findAll();
for (Account account : acts) {
System.out.println(account);
}
} @Test
public void testSave() {
actDao.saveOrUpdate(new Account("xx",12.0));
} @Test
public void testUpdate() {
actDao.saveOrUpdate(new Account(8,"xx",22.0));
} @Test
public void testDelete() {
actDao.delete(new Account(8,"xx",22.0));
} }
Spring 框架下的 JDBC的更多相关文章
- Spring 框架下 (增 删 改 )基本操作
//applicationContext.xml 配置文件 <?xml version="1.0" encoding="UTF-8"?><be ...
- Spring框架下Junit测试
Spring框架下Junit测试 一.设置 1.1 目录 设置源码目录和测试目录,这样在设置产生测试方法时,会统一放到一个目录,如果没有设置测试目录,则不会产生测试代码. 1.2 增加配置文件 Res ...
- 深入剖析 RabbitMQ —— Spring 框架下实现 AMQP 高级消息队列协议
前言 消息队列在现今数据量超大,并发量超高的系统中是十分常用的.本文将会对现时最常用到的几款消息队列框架 ActiveMQ.RabbitMQ.Kafka 进行分析对比.详细介绍 RabbitMQ 在 ...
- Spring框架下的单元测试方法
介绍在Spring的框架下,做单元测试的两种办法. 一.使用spring中对Junit框架的整合功能 除了junit4和spring的jar包,还需要spring-test.jar.引入如下依赖: & ...
- Spring框架下的定时任务quartz框架的使用
手头的这个项目需要用到定时任务,但之前没接触过这东西,所以不太会用,从网上找资料,大致了解了一下,其实也不难.Java的定时任务实现有三种,一种是使用JDK自带的Timer那个类来实现,另一种是使用q ...
- Spring 框架系列之 JDBC 整合实例
微信公众号:compassblog 欢迎关注.转发,互相学习,共同进步! 有任何问题,请后台留言联系! 1.Spring框架整合 DAO 模板 JDBC:org.springframework.jdb ...
- Spring框架之演示JDBC的模板类
1. 步骤一:创建数据库的表结构 create database spring_day03; use spring_day03; create table t_account( id int prim ...
- 关于Jersey框架下的Aop日志 和Spring 框架下的Aop日志
摘要 最近新接手的项目经常要查问题,但是,前面一拨人,日志打的非常乱,好多就根本没有打日志,所以弄一个AOP统一打印一下 请求数据和响应数据 框架 spring+springmvc+jersey 正文 ...
- 解决Spring框架下中文乱码的问题
在使用了Spring框架下回发现很多表单交互的地方会发生乱码,而且写到数据库中也是乱码,这其实还是字符编码的问题,在我们还在用自己写的servlet的时候,直接在request和response加上字 ...
随机推荐
- 纯手工搭建K8s(单节点)
准备说明: 因为为纯手动搭建,所以针对安装时需要的一些安装包需提前下载好 cfssl_linux-amd64. cfssljson_linux-amd64. cfssl-certinfo_linux- ...
- Ceph 提供iSCSI存储
Tgtd+Ceph部署 一.yum安装tgt [root@c720181 ~]# yum --enablerepo=epel -y install scsi-target-utils libxslt ...
- R语言计算IV值
更多大数据分析.建模等内容请关注公众号<bigdatamodeling> 在对变量分箱后,需要计算变量的重要性,IV是评估变量区分度或重要性的统计量之一,R语言计算IV值的代码如下: Ca ...
- 基于iCamera测试AR0134 960p 全局快门相机模块小结
基于iCamera测试AR0134 960p 全局快门相机模块小结 首先看看此模块的特性 AR0134 全局曝光 CMOS模块 1280*960像素 5.3 V/lux-sec 摄像头模块实物靓照(上 ...
- Python发送邮件以及对其封装
对Python发送邮件进行封装 Python发送邮件分为四步 连接到smtp服务器 登陆smtp服务器 准备邮件 发送邮件 导入所需要的包 import smtplib from email.mime ...
- 【Canvas】311- 解决 canvas 在高清屏中绘制模糊的问题
点击上方"前端自习课"关注,学习起来~ 一.问题分析 使用 canvas 绘制图片或者是文字在 Retina 屏中会非常模糊.如图: 因为 canvas 不是矢量图,而是像图片一样 ...
- 《JavaScript 正则表达式迷你书》知识点小抄本
介绍 这周开始学习老姚大佬的<JavaScript 正则表达式迷你书> , 然后习惯性的看完一遍后,整理一下知识点,便于以后自己重新复习. 我个人觉得:自己整理下来的资料,对于知识重现,效 ...
- python学习-继承
# 继承# 你的是我的,我的还是我的 class Animal: def __init__(self,name,private_v1): self.name = name self._private_ ...
- Harbor搭建企业级docker仓库
一. Harbor简介 1.1 Harbor介绍 Harbor是一个用于存储和分发Docker镜像的企业级Registry服务器,通过添加一些企业必需的功能特性,例如安全.标识和管理等,扩展了开源Do ...
- native C++ 动态调用.NET DLL
关于这个问题找了好多地方,都只有第二种解决办法,可是我要返回一个字符串,没办法,继续找,最后还是在http://blogs.msdn.com/b/msdnforum/archive/2010/07/0 ...