11.Spring——JDBC框架

本文内容纲要:

- 1.JDBC 框架概述

- 2.Spring JDBC 示例

- 3.Spring 中 SQL 的存储过程

- 1.JDBC 框架概述

- JdbcTemplate 类

- 配置数据源

- 数据访问对象(DAO)

- 执行 SQL 语句

- 执行 DDL 语句

- Spring JDBC 框架例子

- 2.Spring JDBC 示例

- 3.Spring 中 SQL 的存储过程

- 执行 DDL 语句

1.JDBC 框架概述

2.Spring JDBC 示例

3.Spring 中 SQL 的存储过程

4.jdbc具体使用

5.执行 DDL 语句

1.JDBC 框架概述

在使用普通的 JDBC 数据库时,就会很麻烦的写不必要的代码来处理异常,打开和关闭数据库连接等。但 Spring JDBC 框架负责所有的低层细节,从开始打开连接,准备和执行 SQL 语句,处理异常,处理事务,到最后关闭连接。

所以当从数据库中获取数据时,你所做的是定义连接参数,指定要执行的 SQL 语句,每次迭代完成所需的工作。

Spring JDBC 提供几种方法和数据库中相应的不同的类与接口。我将给出使用 JdbcTemplate 类框架的经典和最受欢迎的方法。这是管理所有数据库通信和异常处理的中央框架类。

JdbcTemplate 类

JdbcTemplate 类执行 SQL 查询、更新语句和存储过程调用,执行迭代结果集和提取返回参数值。它也捕获 JDBC 异常并转换它们到 org.springframework.dao 包中定义的通用类、更多的信息、异常层次结构。

JdbcTemplate 类的实例是线程安全配置的。所以你可以配置 JdbcTemplate 的单个实例,然后将这个共享的引用安全地注入到多个 DAOs 中。

使用 JdbcTemplate 类时常见的做法是在你的 Spring 配置文件中配置数据源,然后共享数据源 bean 依赖注入到 DAO 类中,并在数据源的设值函数中创建了 JdbcTemplate。

配置数据源

我们在数据库 TEST 中创建一个数据库表 Student。假设你正在使用 MySQL 数据库,如果你使用其他数据库,那么你可以改变你的 DDL 和相应的 SQL 查询。

CREATE TABLE Student(

ID INT NOT NULL AUTO_INCREMENT,

NAME VARCHAR(20) NOT NULL,

AGE INT NOT NULL,

PRIMARY KEY (ID)

);

现在,我们需要提供一个数据源到 JdbcTemplate 中,所以它可以配置本身来获得数据库访问。你可以在 XML 文件中配置数据源,其中一段代码如下所示:

<bean id="dataSource"

class="org.springframework.jdbc.datasource.DriverManagerDataSource">

<property name="driverClassName" value="com.mysql.jdbc.Driver"/>

<property name="url" value="jdbc:mysql://localhost:3306/TEST"/>

<property name="username" value="root"/>

<property name="password" value="password"/>

</bean>

数据访问对象(DAO)

DAO 代表常用的数据库交互的数据访问对象。DAOs 提供一种方法来读取数据并将数据写入到数据库中,它们应该通过一个接口显示此功能,应用程序的其余部分将访问它们。

在 Spring 中,数据访问对象(DAO)支持很容易用统一的方法使用数据访问技术,如 JDBC、Hibernate、JPA 或者 JDO。

执行 SQL 语句

我们看看如何使用 SQL 和 jdbcTemplate 对象在数据库表中执行 CRUD(创建、读取、更新和删除)操作。

//查询一个整数类型:

String SQL = "select count(*) from Student";

int rowCount = jdbcTemplateObject.queryForInt( SQL );

//查询一个 long 类型:

String SQL = "select count(*) from Student";

long rowCount = jdbcTemplateObject.queryForLong( SQL );

//一个使用绑定变量的简单查询:

String SQL = "select age from Student where id = ?";

int age = jdbcTemplateObject.queryForInt(SQL, new Object[]{10});

//查询字符串:

String SQL = "select name from Student where id = ?";

String name = jdbcTemplateObject.queryForObject(SQL, new Object[]{10}, String.class);

//查询并返回一个对象:

String SQL = "select * from Student where id = ?";

Student student = jdbcTemplateObject.queryForObject(SQL,

new Object[]{10}, new StudentMapper());

public class StudentMapper implements RowMapper<Student> {

public Student mapRow(ResultSet rs, int rowNum) throws SQLException {

Student student = new Student();

student.setID(rs.getInt("id"));

student.setName(rs.getString("name"));

student.setAge(rs.getInt("age"));

return student;

}

}

//查询并返回多个对象:

String SQL = "select * from Student";

List<Student> students = jdbcTemplateObject.query(SQL,

new StudentMapper());

public class StudentMapper implements RowMapper<Student> {

public Student mapRow(ResultSet rs, int rowNum) throws SQLException {

Student student = new Student();

student.setID(rs.getInt("id"));

student.setName(rs.getString("name"));

student.setAge(rs.getInt("age"));

return student;

}

}

//在表中插入一行:

String SQL = "insert into Student (name, age) values (?, ?)";

jdbcTemplateObject.update( SQL, new Object[]{"Zara", 11} );

//更新表中的一行:

String SQL = "update Student set name = ? where id = ?";

jdbcTemplateObject.update( SQL, new Object[]{"Zara", 10} );

//从表中删除一行:

String SQL = "delete Student where id = ?";

jdbcTemplateObject.update( SQL, new Object[]{20} );

执行 DDL 语句

你可以使用 jdbcTemplate 中的 execute(..) 方法来执行任何 SQL 语句或 DDL 语句。下面是一个使用 CREATE 语句创建一个表的示例:

String SQL = "CREATE TABLE Student( " +

"ID INT NOT NULL AUTO_INCREMENT, " +

"NAME VARCHAR(20) NOT NULL, " +

"AGE INT NOT NULL, " +

"PRIMARY KEY (ID));"

jdbcTemplateObject.execute( SQL );

Spring JDBC 框架例子

基于上述概念,让我们看看一些重要的例子来帮助你理解在 Spring 中使用 JDBC 框架:

序号例子 & 描述
1Spring JDBC Example

这个例子将解释如何编写一个简单的基于 Spring 应用程序的 JDBC。

2SQL Stored Procedure in Spring

学习在使用 Spring 中的 JDBC 时如何调用 SQL 存储过程。

2.Spring JDBC 示例

详见:https://www.w3cschool.cn/wkspring/iuck1mma.html

3.Spring 中 SQL 的存储过程

SimpleJdbcCall 类可以被用于调用一个包含 IN 和 OUT 参数的存储过程。你可以在处理任何一个 RDBMS 时使用这个方法,就像 Apache Derby, DB2, MySQL, Microsoft SQL Server, Oracle,和 Sybase。

为了了解这个方法,我们使用 Student 表,它可以在 MySQL TEST 数据库中使用下面的 DDL 进行创建:

CREATE TABLE Student(

ID INT NOT NULL AUTO_INCREMENT,

NAME VARCHAR(20) NOT NULL,

AGE INT NOT NULL,

PRIMARY KEY (ID)

);

下一步,考虑接下来的 MySQL 存储过程,该过程使用 学生 Id 并且使用 OUT 参数返回相应的学生的姓名和年龄。所以让我们在你的 TEST 数据库中使用 MySQL 命令提示符创建这个存储过程:

DELIMITER $$

DROP PROCEDURE IF EXISTS `TEST`.`getRecord` $$

CREATE PROCEDURE `TEST`.`getRecord` (

IN in_id INTEGER,

OUT out_name VARCHAR(20),

OUT out_age INTEGER)

BEGIN

SELECT name, age

INTO out_name, out_age

FROM Student where id = in_id;

END $$

DELIMITER ;

详见:https://www.w3cschool.cn/wkspring/3yh61mmc.html

4.jdbc具体使用

jdbc.properties文件内容如下:

#database connection config

jdbc.driver = com.mysql.jdbc.Driver

jdbc.url = jdbc:mysql://localhost:3306/device?useUnicode=true&characterEncoding=utf-8

jdbc.username = root

jdbc.password =

在xml文件中,导入这个属性文件以及配置c3p0数据源:

<?xml version="1.0" encoding="UTF-8"?>

<beans xmlns="http://www.springframework.org/schema/beans"

xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"

xmlns:jee="http://www.springframework.org/schema/jee"

xmlns:tx="http://www.springframework.org/schema/tx"

xmlns:context="http://www.springframework.org/schema/context"

xmlns:aop="http://www.springframework.org/schema/aop"

xsi:schemaLocation="

http://www.springframework.org/schema/aop

http://www.springframework.org/schema/aop/spring-aop-4.2.xsd

http://www.springframework.org/schema/beans

http://www.springframework.org/schema/beans/spring-beans-4.2.xsd

http://www.springframework.org/schema/tx

http://www.springframework.org/schema/tx/spring-tx-4.2.xsd

http://www.springframework.org/schema/jee

http://www.springframework.org/schema/jee/spring-jee-4.2.xsd

http://www.springframework.org/schema/context

http://www.springframework.org/schema/context/spring-context-4.2.xsd">

<!-- 导入资源文件 -->

<context:property-placeholder location="classpath:test/jdbc.properties" />

<!--c3p0 pool -->

<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource"

destroy-method="close">

<property name="driverClass" value="${jdbc.driver}" /> <!--数据库连接驱动 -->

<property name="jdbcUrl" value="${jdbc.url}" /> <!--数据库地址 -->

<property name="user" value="${jdbc.username}" /> <!--用户名 -->

<property name="password" value="${jdbc.password}" /> <!--密码 -->

<property name="maxPoolSize" value="40" /> <!--最大连接数 -->

<property name="minPoolSize" value="1" /> <!--最小连接数 -->

<property name="initialPoolSize" value="10" /> <!--初始化连接池内的数据库连接 -->

<property name="maxIdleTime" value="20" /> <!--最大空闲时间 -->

</bean>

<!-- 配置 spring 的 JdbcTemplate -->

<bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">

<property name="dataSource" ref="dataSource"></property>

</bean>

</beans>

测试类

package com.my.dm.test;

import java.util.List;

import java.util.UUID;

import org.springframework.context.ConfigurableApplicationContext;

import org.springframework.context.support.ClassPathXmlApplicationContext;

import org.springframework.jdbc.core.JdbcTemplate;

import com.my.dm.model.Device;

import com.my.dm.model.DeviceMapper;

public class TestJDBC {

public static void main(String[] args) {

// TODO Auto-generated method stub

ConfigurableApplicationContext context = new ClassPathXmlApplicationContext("test/aop.xml");

JdbcTemplate jdbcTemplate =(JdbcTemplate) context.getBean("jdbcTemplate");

//查询行数

String sql1 = "select count(*) from device";

Integer rowCount1 = jdbcTemplate.queryForObject(sql1, Integer.class);

System.out.println("所有记录条数为 : " + rowCount1);

//一个使用绑定变量的简单查询:

String sql2 = "select count(*) from device where AREA = ?";

Integer rowCount2 = jdbcTemplate.queryForObject(sql2,new Object[]{"西安"} ,Integer.class);

System.out.println("西安的记录条数为 : " + rowCount2);

//查询并返回一个对象:

String sql3 = "select * from device where DEVICE_IP = ?";

Device device = jdbcTemplate.queryForObject(sql3,new Object[]{"4.154.133.119"} ,new DeviceMapper());

System.out.println(device);

////查询并返回多个对象:

String sql4 = "select * from device where AREA = ?";

List<Device> devices = jdbcTemplate.query(sql4,new Object[]{"西安"} ,new DeviceMapper());

System.out.println(devices.size());

//在表中插入一行:

String sql5 = "insert into image (IMG_ID, IMG_NAME,IMG_SIZE) values (?, ?,?)";

int num5 = jdbcTemplate.update( sql5, new Object[]{UUID.randomUUID().toString().replace("-", ""),"TestA", 11} );

System.out.println("Insert 受影响的行数为 :" + num5);

//更新表中的一行:

String sql6 = "update image set IMG_NAME = ? where IMG_ID = ?";

int num6 = jdbcTemplate.update( sql6, new Object[]{"New Name","2705dbde4a694926b59318a96e04cce2"} );

System.out.println("update 受影响的行数为 :" + num6);

// 从表中删除

String sql7 = "delete from image where IMG_NAME = ?";

int num7 = jdbcTemplate.update(sql7, new Object[] { "TestA"});

System.out.println("delete 受影响的行数为 :" + num7);

}

}

package com.my.dm.model;

import java.sql.ResultSet;

import java.sql.SQLException;

import org.springframework.jdbc.core.RowMapper;

public class DeviceMapper implements RowMapper<Device> {

@Override

public Device mapRow(ResultSet rs, int rowNum) throws SQLException {

// TODO Auto-generated method stub

Device device = new Device();

device.setId(rs.getString("ID"));

device.setArea(rs.getString("AREA"));

device.setDeviceIp(rs.getString("DEVICE_IP"));

//...

return device;

}

}

批量执行操作

/**

* 测试批量更新操作

* 最后一个参数是 Object[] 的 List 类型:因为修改一条记录需要一个 Object 数组,修改多条记录就需要一个 List 来存放多个数组。

*/

@Test

public void testBatchUpdate() {

String sql = "INSERT INTO employees(last_name, email, dept_id) VALUES(?,?,?)";

List<Object[]> batchArgs = new ArrayList<>();

batchArgs.add(new Object[]{"AA", "aa@atguigu.com", 1});

batchArgs.add(new Object[]{"BB", "bb@atguigu.com", 2});

batchArgs.add(new Object[]{"CC", "cc@atguigu.com", 3});

batchArgs.add(new Object[]{"DD", "dd@atguigu.com", 3});

batchArgs.add(new Object[]{"EE", "ee@atguigu.com", 2});

jdbcTemplate.batchUpdate(sql, batchArgs);

}

/**

* 从数据库中获取一条记录,实际得到对应的一个对象

* 注意:不是调用 queryForObject(String sql, Class<Employee> requiredType, Object... args) 方法!

* 而需要调用 queryForObject(String sql, RowMapper<Employee> rowMapper, Object... args)

* 1、其中的 RowMapper 指定如何去映射结果集的行,常用的实现类为 BeanPropertyRowMapper

* 2、使用 SQL中的列的别名完成列名和类的属性名的映射,例如 last_name lastName

* 3、不支持级联属性。 JdbcTemplate 只能作为一个 JDBC 的小工具, 而不是 ORM 框架

*/

@Test

public void testQueryForObject() {

String sql = "SELECT id, last_name lastName,email,dept_id as \"department.id\" FROM employees WHERE ID = ?";

RowMapper<Employee> rowMapper = new BeanPropertyRowMapper<>(Employee.class);

//在将数据装入对象时需要调用set方法。

Employee employee = jdbcTemplate.queryForObject(sql, rowMapper, 1);

System.out.println(employee);

}

/**

* 一次查询多个对象

* 注意:调用的不是 queryForList 方法

*/

@Test

public void testQueryForList() {

String sql = "SELECT id, last_name lastName, email FROM employees WHERE id > ?";

RowMapper<Employee> rowMapper = new BeanPropertyRowMapper<>(Employee.class);

List<Employee> employees = jdbcTemplate.query(sql, rowMapper,5);

System.out.println(employees);

}

/**

* 获取单个列的值或做统计查询

* 使用 queryForObject(String sql, Class<Long> requiredType)

*/

@Test

public void testQueryForObject2() {

String sql = "SELECT count(id) FROM employees";

long count = jdbcTemplate.queryForObject(sql, Long.class);

System.out.println(count);

}

总结:JdbcTemplate是Spring框架自带的对JDBC操作的封装,目的是提供统一的模板方法使对数据库的操作更加方便、友好,效率也不错。但是功能还是不够强大(比如不支持级联属性),

在实际应用中还需要和hibernate、mybaties等框架混合使用。

执行 DDL 语句

你可以使用 jdbcTemplate 中的 execute(..) 方法来执行任何 SQL 语句或 DDL 语句。下面是一个使用 CREATE 语句创建一个表的示例:

String SQL = "CREATE TABLE Student( " +

"ID INT NOT NULL AUTO_INCREMENT, " +

"NAME VARCHAR(20) NOT NULL, " +

"AGE INT NOT NULL, " +

"PRIMARY KEY (ID));"

jdbcTemplateObject.execute( SQL );

本文内容总结:1.JDBC 框架概述,2.Spring JDBC 示例,3.Spring 中 SQL 的存储过程,1.JDBC 框架概述,JdbcTemplate 类,配置数据源,数据访问对象(DAO),执行 SQL 语句,执行 DDL 语句,Spring JDBC 框架例子,2.Spring JDBC 示例,3.Spring 中 SQL 的存储过程,执行 DDL 语句,

原文链接:https://www.cnblogs.com/lukelook/p/9618225.html

以上是 11.Spring——JDBC框架 的全部内容, 来源链接: utcz.com/z/362663.html

回到顶部