https://www.tutorialspoint.com/spring/spring_jdbc_framework.htm

Spring - JDBC Framework Overview

While working with the database using plain old JDBC, it becomes cumbersome to write unnecessary code to handle exceptions, opening and closing database connections, etc. However, Spring JDBC Framework takes care of all the low-level details starting from opening the connection, prepare and execute the SQL statement, process exceptions, handle transactions and finally close the connection.

So what you have to do is just define the connection parameters and specify the SQL statement to be executed and do the required work for each iteration while fetching data from the database.

Spring JDBC provides several approaches and correspondingly different classes to interface with the database. I'm going to take classic and the most popular approach which makes use of JdbcTemplate class of the framework. This is the central framework class that manages all the database communication and exception handling.

JdbcTemplate Class

The JDBC Template class executes SQL queries, updates statements, stores procedure calls, performs iteration over ResultSets, and extracts returned parameter values. It also catches JDBC exceptions and translates them to the generic, more informative, exception hierarchy defined in the org.springframework.dao package.

Instances of the JdbcTemplate class are threadsafe once configured. So you can configure a single instance of a JdbcTemplate and then safely inject this shared reference into multiple DAOs.

A common practice when using the JDBC Template class is to configure a DataSource in your Spring configuration file, and then dependency-inject that shared DataSource bean into your DAO classes, and the JdbcTemplate is created in the setter for the DataSource.

Configuring Data Source

Let us create a database table Student in our database TEST. We assume you are working with MySQL database, if you work with any other database then you can change your DDL and SQL queries accordingly.

CREATE TABLE Student(
ID INT NOT NULL AUTO_INCREMENT,
NAME VARCHAR(20) NOT NULL,
AGE INT NOT NULL,
PRIMARY KEY (ID)
);

Now we need to supply a DataSource to the JDBC Template so it can configure itself to get database access. You can configure the DataSource in the XML file with a piece of code as shown in the following code snippet −

<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>

Data Access Object (DAO)

DAO stands for Data Access Object, which is commonly used for database interaction. DAOs exist to provide a means to read and write data to the database and they should expose this functionality through an interface by which the rest of the application will access them.

The DAO support in Spring makes it easy to work with data access technologies like JDBC, Hibernate, JPA, or JDO in a consistent way.

Executing SQL statements

Let us see how we can perform CRUD (Create, Read, Update and Delete) operation on database tables using SQL and JDBC Template object.

Querying for an integer

String SQL = "select count(*) from Student";
int rowCount = jdbcTemplateObject.queryForInt( SQL );

Querying for a long

String SQL = "select count(*) from Student";
long rowCount = jdbcTemplateObject.queryForLong( SQL );

A simple query using a bind variable

String SQL = "select age from Student where id = ?";
int age = jdbcTemplateObject.queryForInt(SQL, new Object[]{10});

Querying for a String

String SQL = "select name from Student where id = ?";
String name = jdbcTemplateObject.queryForObject(SQL, new Object[]{10}, String.class);

Querying and returning an object

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;
}
}

Querying and returning multiple objects

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;
}
}

Inserting a row into the table

String SQL = "insert into Student (name, age) values (?, ?)";
jdbcTemplateObject.update( SQL, new Object[]{"Zara", 11} );

Updating a row into the table

String SQL = "update Student set name = ? where id = ?";
jdbcTemplateObject.update( SQL, new Object[]{"Zara", 10} );

Deleting a row from the table

String SQL = "delete Student where id = ?";
jdbcTemplateObject.update( SQL, new Object[]{20} );

Executing DDL Statements

You can use the execute(..) method from jdbcTemplate to execute any SQL statements or DDL statements. Following is an example to use CREATE statement to create a table −

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 Framework Examples

Based on the above concepts, let us check few important examples which will help you in understanding usage of JDBC framework in Spring −

Sr.No. Example & Description
1 Spring JDBC Example

This example will explain how to write a simple JDBC-based Spring application.

2 SQL Stored Procedure in Spring

Learn how to call SQL stored procedure while using JDBC in

handle exceptions, opening and closing database connections的更多相关文章

  1. com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: Unknown database 'smvch'

    1.错误描述 INFO:2015-05-01 14:20:44[main] - Initializing c3p0 pool... com.mchange.v2.c3p0.ComboPooledDat ...

  2. 回滚原理 Since database connections are thread-local, this is thread-safe.

    mysql django 实践: django @transaction.atomic 机制分析  1.数据库清空表Tab 2.请求django-view        @transaction.at ...

  3. com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: Unknown database 'user'

    1.错误描述 2014-7-12 21:06:05 com.mchange.v2.c3p0.impl.AbstractPoolBackedDataSource getPoolManager 信息: I ...

  4. com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: Unknown database &#39;user&#39;

    1.错误描写叙述 2014-7-12 21:06:05 com.mchange.v2.c3p0.impl.AbstractPoolBackedDataSource getPoolManager 信息: ...

  5. org.apache.ibatis.exceptions.PersistenceException: ### Error querying database. Cause: com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: You have an error in your SQL syntax; check the manu

    这个是sql 语句 错误     仔细检查 SQL语句是否写错了 org.apache.ibatis.exceptions.PersistenceException: ### Error queryi ...

  6. ERROR 000732:Output Geodatabase:Dataset Database Connections\Connection to localhost.sde\SDE.Dataset does not exist or is not supported

    ArcCatalog 10中向SDE 数据集导入要素类时,出错:ERROR 000732:Output Geodatabase:Dataset Database Connections\Connect ...

  7. eclipse中创建DataBase Connections

    1.window --> show view --> other --> Data Management --> Data Exploerer --> ok: 2.右键单 ...

  8. org.apache.ibatis.exceptions.PersistenceException: ### Error querying database. Cause: com.mysql.jdbc.exceptions.jdbc4.CommunicationsException: Communications link failure The last packet sent succ

    数据库 没有开启  连接失败 org.apache.ibatis.exceptions.PersistenceException: ### Error querying database. Cause ...

  9. <Closing connections idle longer than 60000 MILLISECONDS> <Closing expired connections>

    日志信息如下: 2017-07-05 18:28:34 -18705 [idle_connection_reaper] DEBUG   - Closing expired connections 20 ...

随机推荐

  1. (转)YV12 and NV12

    用videoCapture和IAMStreamConfig拿到的支持的格式列表.发现支持2中图像格式,YV12和NV12.具体是怎么样的内存分布不知道.查了些文档.自己修改了几个图.看出了点端倪 YV ...

  2. Loadrunner 9.5_webservice(SOAP)性能测试

    WebService定义:Webservice是一种新的使用基于XML标准和协议来交换信息的WEB应用程序.是基于SOAP(简单对象访问协议)消息的应该协议,只是为WEB页面或可执行程序提供编程接口. ...

  3. Swing中如何比较好的判断鼠标左键双击

    import java.awt.Toolkit; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; im ...

  4. 放在github pages上的静态网站怎么取消绑定自定义域名?

    使用GitHub Pages搭建的静态网站绑定了自定义域名操作,但是想反悔怎么办? 删除CNAME文件,重新删除仓库,新建后均不行~ 解决办法:清除一下浏览器缓存,或者用别的浏览器打开就好了,因为之前 ...

  5. Java精选笔记_国际化

    国际化 什么是国际化 指软件在开发时就应该具备支持多种语言和地区的功能,当应对不同国家和地区的用户访问,针对不同国家和地区的用户,提供相应的.符合来访者阅读习惯的页面和数据. 由于国际化interna ...

  6. Java精选笔记_Java API

    String类 String类的初始化 String是一个特殊的对象,一旦被初始化,就不会被改变 1.使用字符串常量直接初始化一个String对象 String  s1="abc" ...

  7. SegmentedControl的使用

    原文 http://blog.csdn.net/hmt20130412/article/details/38390493 @UISegmentedControl类似于UIButton,它可以提供多个选 ...

  8. DAGDGC特殊调弦

    DAGDGC 特殊调弦 重要知识点: 1)音高从高到低排序为:BAGFEDC 2)吉他标准音是(1到6弦) EBGDAE 3)吉他同一弦,每相差一个品级,相差是半个音 调弦方法:1)第一弦(E-> ...

  9. C#中的方法,方法的重载,以及几个关键字

    嘿嘿,今天来的早点啦,主要有问题解决不了,希望看到的亲们知道怎么整的给我说下,先谢谢哦:-D <一>首先复习了三元表达式:即  表达式1,表达式2,表达式3: 举例: bool resul ...

  10. nutch 存储到数据库

    就像我们知道的一样,nutch是一个架构在lucene之上的网络爬虫+搜索引擎. 是由lucene的作者在lucene基础之上开发,并整合了hadoop,实现在分布式云计算,使用google标准的HF ...