Spring使用原生JDBC
Spring使用原生JDBC
为加深对Spring解耦的理解,本次实验学习用Spring连接JDBC
一、POM配置文件
pom.xml
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>fanghao</groupId>
<artifactId>myspring</artifactId>
<version>1.0-SNAPSHOT</version>
<packaging>jar</packaging>
<name>myspring</name>
<url>http://maven.apache.org</url>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>3.8.1</version>
<scope>test</scope>
</dependency>
<!--Spring Context-->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>5.0.5.RELEASE</version>
</dependency>
<!-- https://mvnrepository.com/artifact/mysql/mysql-connector-java -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.9-rc</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>5.0.5.RELEASE</version>
</dependency>
</dependencies>
</project>
二、用户类
Customer.java
package newHello.customer;
public class Customer {
private String name;
private int age;
public Customer(String name, int age) {
this.name = name;
this.age = age;
}
@Override
public String toString() {
return "Customer{" +
"name=" + name +
", age=" + age +
'}';
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
}
三、用户DAO接口
CustomerDAO.java
package newHello.customer;
/**
* DAO(Data Access Object)数据存取对象
*/
public interface CustomerDAO {
void insert(Customer customer);
Customer findByCustomerId(int custId);
}
四、用户DAO接口实现类
package newHello.customer;
import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
public class JdbcCustomerDAO implements CustomerDAO {
private DataSource dataSource;
public void setDataSource(DataSource dataSource) {
this.dataSource = dataSource;
}
/**
* 使用prepareStatement拼接SQL
* @param customer 获取输入对象的属性
*/
public void insert(Customer customer) {
String sql = "insert into CUSTOMER " +
"(NAME, AGE) VALUES(?, ?)";
Connection conn = null;
try {
conn = dataSource.getConnection();
PreparedStatement ps = conn.prepareStatement(sql);
ps.setString(1, customer.getName());
ps.setInt(2, customer.getAge());
ps.executeUpdate();
ps.close();
} catch (SQLException e) {
e.printStackTrace();
} finally {
if (conn != null)
try {
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
public Customer findByCustomerId(int custId) {
String sql = "select * from CUSTOMER where CUST_ID = ?";
Connection conn = null;
try {
conn = dataSource.getConnection();
PreparedStatement ps = conn.prepareStatement(sql);
ps.setInt(1, custId);
Customer customer = null;
ResultSet rs = ps.executeQuery();
if (rs.next()) {
customer = new Customer(
rs.getString("NAME"),
rs.getInt("Age")
);
}
rs.close();
ps.close();
return customer;
} catch (SQLException e) {
e.printStackTrace();
} finally {
if (conn != null) {
try {
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
return null;
}
}
五、资源文件
资源文件主要做配置,管理java bean
➜ resources tree .
.
├── Spring-Customer.xml
├── Spring-Datasource.xml
└── Spring-Module.xml
0 directories, 3 files
5.1 Spring-Customer.xml
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-2.5.xsd">
<!--配置用户接口的实现类JdbcCustomerDAO-->
<bean id="customerDAO" class="newHello.customer.JdbcCustomerDAO">
<property name="dataSource" ref="dataSource" />
</bean>
</beans>
5.2 Spring-Datasource.xml
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-2.5.xsd">
<!--配置数据库驱动-->
<bean id="dataSource"
class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="com.mysql.cj.jdbc.Driver" />
<property name="url" value="jdbc:mysql://localhost:3306/test" />
<property name="username" value="root" />
<property name="password" value="mysql123" />
</bean>
</beans>
5.3 Spring-Module.xml
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-2.5.xsd">
<!--管理要导入的XML配置文件-->
<import resource="Spring-Datasource.xml" />
<import resource="Spring-Customer.xml" />
</beans>
六、应用启动程序
App.java
package newHello.customer;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class App {
public static void main(String[] args) {
// 根据XML配置文件生成应用上下文
ApplicationContext context =
new ClassPathXmlApplicationContext("Spring-Module.xml");
// 读取customerDAO的JavaBean,转型为customerDAO
CustomerDAO customerDAO = (CustomerDAO) context.getBean("customerDAO");
// 用封装好DAO进行类似ORM的操作
customerDAO.insert(new Customer("Jack", 21));
customerDAO.insert(new Customer("Tom", 24));
customerDAO.insert(new Customer("Jane", 25));
Customer customer = customerDAO.findByCustomerId(2);
System.out.println(customer);
}
}
七、运行结果
Customer{name=Tom, age=24}
Spring使用原生JDBC的更多相关文章
- 【JAVA - SSM】之MyBatis与原生JDBC、Hibernate访问数据库的比较
首先来看一下原生JDBC访问数据库的代码: public static void main(String[] args) { // 数据库连接 Connection connection = null ...
- 4、原生jdbc链接数据库常用资源名
原生jdbc链接数据库要素:#MySql:String url="jdbc:mysql://localhost:3306/数据库名";String name="root& ...
- 【JavaEE】之MyBatis与原生JDBC、Hibernate访问数据库的比较
首先来看一下原生JDBC访问数据库的代码: public static void main(String[] args) { // 数据库连接 Connection connection = null ...
- 使用Spring JDBCTemplate简化JDBC的操作
使用Spring JDBCTemplate简化JDBC的操作 接触过JAVA WEB开发的朋友肯定都知道Hibernate框架,虽然不否定它的强大之处,但个人对它一直无感,总感觉不够灵活,太过臃肿了. ...
- 【转】在Spring中基于JDBC进行数据访问时怎么控制超时
http://www.myexception.cn/database/1651797.html 在Spring中基于JDBC进行数据访问时如何控制超时 超时分类 超时根据作用域可做如下层级划分: Tr ...
- 原生Jdbc操作Mysql数据库开发步骤
原生Jdbc操作Mysql数据库开发步骤 原生的Jdbc就是指,不使用任何框架,仅用java.sql包下的方法实现数据库查询等的操作. 下面是开发步骤: 1.导入数据库驱动包 ...
- spring框架总结(04)----介绍的是Spring中的JDBC模板
1.1 Jdbc模板概述 它是spring框架中提供的一个对象,是对原始Jdbc API对象的简单封装.spring框架为我们提供了很多的操作模板类,入下图所示: 我们今天的主角在spring-jd ...
- Spring 对JDBC操作的支持
1.Spring 对JDBC操作的支持 Spring对jdbc技术提供了很好的支持,体现在: 1.Spring对c3p0连接池的支持很完善 2.Spring对jdbc提供了jdbcTemplate,来 ...
- Spring中使用JDBC
Spring中的数据库异常体系 使用JDBC(不使用Spring)的时候,我们需要强制捕获SQLException,否则无法使用JDBC处理任何事情.SQLException表示尝试访问数据库的时候出 ...
随机推荐
- Leetcode 344. 反转字符串
344. Reverse String 解题代码: class Solution { public: void reverseString(vector<char>& s) { , ...
- 【C++ Primer | 07】泛型算法
定制操作 #include <iostream> #include <string> #include <vector> #include <algorith ...
- webpack学习笔记--多种配置类型
除了通过导出一个 Object 来描述 Webpack 所需的配置外,还有其它更灵活的方式,以简化不同场景的配置. 下面来一一介绍它们. 导出一个 Function 在大多数时候你需要从同一份源代码中 ...
- BFC的形成和排版规则
何为bfc? BFC(Block Formatting Context)直译为“块级格式化范围”.是 W3C CSS 2.1 规范中的一个概念,它决定了元素如何对其内容进行定位,以及与其他元素的关系和 ...
- UICollectionViewController的用法1
UICollectionView 和 UICollectionViewController 类是iOS6 新引进的API,用于展示集合视图,布局更加灵活,可实现多列布局,用法类似于UITableVie ...
- 【AtCoder】Tenka1 Programmer Contest 2019
Tenka1 Programmer Contest 2019 C - Stones 题面大意:有一个01序列,改变一个位置上的值花费1,问变成没有0在1右边的序列花费最少多少 直接枚举前i个都变成0即 ...
- Linux图形化监控网络流量:speedometer查看流量
Speedometer是一个带宽控制台和对数带宽显示的文件下载进度监控,以及一个简单的命令行界面.其目的是测量和显示网络连接或数据存储在文件中的数据率. Speedometer 2.8该版本增加了一个 ...
- Codeforces 886E Maximum Element 组合数学 + dp
我们定义dp[ i ]表示长度为 i 的序列, 最后没有一个==k的时候返回的方案数, 也就是最后强制返回 i 的方案数. 我们能得到dp方程 dp[ i ] = sum(dp[ i - j - ...
- Python 类的内置方法
#!/usr/bin/env python # -*- coding:utf-8 -*- # 作者:Presley # 邮箱:1209989516@qq.com # 时间:2018-11-04 # p ...
- windows下安装Memcached服务器,PHP的memcache扩展
Memcahed 介绍:Memcahed是一个内存缓存服务器 (类似MySQL服务器) 作用:提高web的响应速度,例如缓存数据库查询结果 原理:把数据存到内存中 (提高速度的原因) 教程相关 系统: ...