![jdbctemplate](https://img-blog.csdnimg.cn/img_convert/60d26a8e55745a1416a5a54e441391c8.png)
jdbctemplate
大家好,如果您一直在使用Spring框架,那么您可能知道JdbcTempalte是Spring框架中最有用的类之一。 JdbcTempalte
类提供了许多方便的方法来执行与数据库相关的任务,从而减轻了使用JDBC API的麻烦。 如果您从事过使用JDBC连接到数据库的任何现实生活中的JAva项目,那么您就会知道JDBC API使用起来并不方便,因为它需要大量样板代码。 例如,要执行一个简单的SELECT查询,首先需要创建一个Connection and Statement对象来执行查询,并遍历ResultSet对象来获取查询结果。 最后,您需要关闭所有这些资源以防止Java中的资源泄漏。
通过使用诸如JdbcTemplate之类的类,Spring框架减少了许多此类样板代码。 JdbcTemplate
提供了多种重载方法来执行不同种类SQL查询和执行CRUD操作。
JdbcTemplate实用程序类还广泛使用了变量参数方法,这使在SQL查询中使用PreparedStatment和bind变量非常容易。
在本文中,我将向您展示如何使用JdbcTempalte类查询单个值,使用绑定变量运行查询,如何从数据库检索的数据填充Java对象,如何插入行,如何更新记录,如何删除记录以及如何使用JdbcTempalte运行任何类型SQL查询。
Spring框架中的JdbcTemplate示例
大家好,如果您一直在使用Spring框架,那么您可能知道JdbcTempalte是Spring框架中最有用的类之一。 JdbcTempalte类提供了许多方便的方法来执行与数据库相关的任务,从而减轻了使用JDBC API的麻烦。 如果您从事过使用JDBC连接到数据库的任何现实生活中的JAva项目,那么您就会知道JDBC API使用起来并不方便,因为它需要大量样板代码。 例如,要执行一个简单的SELECT查询,首先需要创建一个Connection and Statement对象来执行查询,并遍历ResultSet对象来获取查询结果。 最后,您需要关闭所有这些资源以防止Java中的资源泄漏。
通过使用诸如JdbcTemplate之类的类,Spring框架减少了许多此类样板代码。 JdbcTemplate提供了多种重载方法来执行不同种类SQL查询和执行CRUD操作。
JdbcTemplate实用程序类还广泛使用了变量参数方法,这使在SQL查询中使用PreparedStatment和bind变量非常容易。
在本文中,我将向您展示如何使用JdbcTempalte类查询单个值,使用绑定变量运行查询,如何从数据库检索的数据填充Java对象,如何插入行,如何更新记录,如何删除记录以及如何使用JdbcTempalte运行任何类型SQL查询。
顺便说一句,我希望您熟悉Spring框架。 如果您不熟悉Spring Framework并且不熟悉Spring API,那么我建议您首先学习Udemy上John Thomson撰写的全面的Spring框架课程,例如Spring Framework 5:Beginner to Guru ,以学习基础知识。 这样可以节省您很多时间。 这也是学习Spring的最新课程,涵盖Spring 5和诸如Reactive Programming之类的新概念。 它也非常实惠,您只需10美元即可购买Udemy的销售。
Spring框架中的JdbcTemplate示例
正如我告诉您的那样,我们将看到JdbcTempalte的多个示例来执行日常查询,但是在此之前,让我们了解表中的架构和数据,以便我们可以验证输出并确定代码是否可以正常工作。预期。
这是我们的数据库和表的外观:
mysql> select from employee;
+--------+----------+---------+--------+
| emp_id | emp_name | dept_id | salary |
+--------+----------+---------+--------+
| 101 | James | 1 | 1000 |
| 102 | kate | 1 | 1200 |
| 103 | Jack | 2 | 1400 |
| 104 | John | 2 | 1450 |
| 105 | Johnny | 3 | 1050 |
| 108 | Alan | 3 | 1150 |
| 106 | Virat | 4 | 850 |
| 107 | Vina | 4 | 700 |
| 109 | joya | 4 | 700 |
| 110 | James | 1 | 1000 |
+--------+----------+---------+--------+
10 rows in set (0.00 sec)
mysql> show tables;
+----------------+
| Tables_in_test |
+----------------+
| books |
| department |
| employee |
+----------------+
3 rows in set (0.09 sec)
并且,这是一些使用Spring框架的JdbcTemplate类与数据库进行交互并运行SQL查询以从表中读取和写入数据的常见示例
1.如何使用JdbcTemplate查询单个值,如count,id等
如果您想运行一个运行诸如count()
, avg()
, max()
和min()
类的聚合函数SQL查询,或者只返回一个整数值,则可以使用JdbcTempalte的queryForInt()方法执行该SQL查询。如下例所示:
int total = jdbcTemplate.queryForInt("SELECT count() FROM employee");
logger.info("Total Employees : " + total);
2.使用JdbcTemplate示例从数据库查询和填充Java对象
如果要运行返回诸如String之类的值对象SQL查询,则可以使用JdbcTempalte类的queryForObject()
方法。 此方法接受有关将返回哪种类型的类查询的参数,然后将结果转换为该对象并返回给调用者
String name = jdbcTemplate.queryForObject("SELECT emp_name
FROM employee where emp_id=?",
new Object[]{103}, String.class);
3.使用JdbcTemplate示例从数据库检索自定义对象
如果您SQL查询将返回诸如Employee
, Order
或任何特定于域的用户对象之类的用户对象,则需要向Roweapper实现提供给queryForObject()方法。 该映射器将告诉JdbcTempalte如何将ResultSet转换为自定义对象。 这是检索自定义对象的示例。
Employee emp = jdbcTemplate.queryForObject("SELECT FROM employee
where emp_id=?",
new Object[]{103},
new EmployeeMapper());
4. JdbcTemplate示例,用于从表中检索对象列表
如果您SQL查询将返回对象列表,而不是仅返回一个对象,则需要使用JdbcTempalte的query()
方法。 这是最通用的方法之一,它可以运行任何类型的查询。 再次将结果转换为自定义对象,您需要提供RowMapper实现,如以下示例所示:
List<Employee> empList = jdbcTemplate.query("SELECT FROM employee
where salary > 500",
new EmployeeMapper());
5.如何使用Spring JdbcTemplate示例在SQL中插入记录
到目前为止,我们已经看到了使用JdbcTemplate的查询方法(例如queryForInt()
, queryForObject()
和query()
本身queryForObject()
从表中读取数据的示例。 现在,您将看到如何将数据写入表中,例如使用JdbcTempalte运行插入,更新和删除查询。 要将数据插入数据库,可以使用JdbcTempalte类的update()
方法,如下所示:
int insertCount = jdbcTemplate.update("INSERT INTO employee
values (?,?,?,?)",
"111", "Peter", "1", "2000" );
6.如何使用Spring JdbcTemplate示例更新SQL中的记录
我们在上一个示例中用于插入数据的更新方法也可以用于在Spring JDBC应用程序中运行更新查询。 这是一个如何使用Spring的JdbcTempalte
类更新特定记录的示例:
int updateCount = jdbcTemplate.update("UPDATE employee
SET dept_id=?
WHERE emp_id=?", "2", "112");
7.如何使用Spring JdbcTemplate删除表中的行
如下所示,也可以使用与运行插入和更新查询相同的更新方法来运行删除查询。 这次,它返回给定SQL查询删除的行数,这与前面的示例中插入和更新的记录数不同。
int deleteCount = jdbcTemplate.update("DELETE FROM employee
WHERE dept_id=?", "1" );
8.使用JdbcTemplate示例执行任何SQL查询
到目前为止,我们已经看到了有关如何使用Spring Framework和JdbcTemplate(如CRUD(创建,读取,更新和删除))运行DML或数据操作查询的示例,但JdbcTemplate还可以运行诸如Create table或Create Index的DDL查询。 JdbcTempalte
类还具有通用的execute()
方法来运行DDL查询,如下所示,其中我们创建了一个名为Book的新表:
jdbcTemplate.execute("create table Books (id integer,
name varchar(50), ISBN integer)");
现在,您已经看到了使用JdbcTempalte的不同方法(例如execute()
, update()
, query()
, queryForObject()
和queryForInt()
的各个示例,让我们看一看完整的程序,您可以在自己喜欢的程序中复制和执行该程序。 IDE。
Java中的Spring Framework JdbcTemplate示例
这是示例程序,它将教您如何在基于Spring的Java应用程序中使用JdbcTemplate。
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;
import javax.sql.DataSource;
import org.apache.log4j.Logger;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import com.test.domain.Employee;
public class JdbcUtil {
private static Logger logger = Logger.getLogger(JdbcUtil.class);
private JdbcTemplate jdbcTemplate;
public void setDataSource(DataSource source){
this.jdbcTemplate = new JdbcTemplate(source);
}
/**
* This method demonstrates 10 JdbcTemplate examples in Spring
*/
public void jdbcTemplateExamples(){
// how to use JdbcTemplate to query for single value e.g. count, id etc
int total = jdbcTemplate.queryForInt("SELECT count() FROM employee");
logger.info("Total Employees : " + total);
//another example to query for single value using bind variable in Java
String name = jdbcTemplate.queryForObject("SELECT emp_name
FROM employee where emp_id=?",
new Object[]{103}, String.class);
logger.info("Name of Employee : " + name);
//JdbcTemplate example to query and populate Java object from database
Employee emp = jdbcTemplate.queryForObject("SELECT FROM employee
where emp_id=?",
new Object[]{103},
new EmployeeMapper());
logger.info(emp);
//JdbcTemplate example to retrieve a list of object from database
List empList = jdbcTemplate.query("SELECT FROM employee
where salary > 500",
new EmployeeMapper());
logger.info("size : " + empList.size() + ", List of Employees : "
+ empList);
// JdbcTemplate Example to INSERT records into database
int insertCount = jdbcTemplate.update("INSERT INTO employee
values (?,?,?,?)",
"111", "Peter", "1", "2000" );
logger.info("number of rows inserted using JdbcTemplate : "
+ insertCount);
// How to update records in SQL using Spring JdbcTemplate example
int updateCount = jdbcTemplate.update("UPDATE employee
SET dept_id=?
where emp_id=?", "2", "112");
logger.info("number of rows updated with JdbcTemplated : "
+ updateCount);
// How to delete rows in a table using Spring JdbcTemplate
int deleteCount = jdbcTemplate.update("DELETE FROM employee
where dept_id=?", "1" );
logger.info("number of rows deleted using JdbcTemplate : "
+ deleteCount);
// JdbcTemplate example to execute any SQL query
jdbcTemplate.execute("create table Books (id integer,
name varchar(50), ISBN integer)");
}
public static void main(String args[]){
ApplicationContext context
= new ClassPathXmlApplicationContext("spring-config.xml");
JdbcUtil jdbcUtil = (JdbcUtil) context.getBean("jdbcUtil");
//calling jdbcTemplateExmaples() to
// demonstrate various ways to use JdbcTemplate in Spring
jdbcUtil.jdbcTemplateExamples();
}
/**
* nested static class to act as RowMapper for Employee object
*/
private static class EmployeeMapper implements RowMapper {
public Employee mapRow(ResultSet rs, int rowNum) throws SQLException {
Employee emp = new Employee();
emp.setId(rs.getInt("emp_id"));
emp.setName(rs.getString("emp_name"));
emp.setDepartmentId(rs.getInt("dept_id"));
emp.setSalary(rs.getInt("salary"));
return emp;
}
}
pre class =“ brush:bash”>输出:2013-01-03 02:47:34,282 0 [main] INFO JdbcUtil –员工总数:7 2013-01-03 02:47:34,313 31 [main] INFO JdbcUtil –名称员工人数:Jack 2013-01-03 02:47:34,313 31 [main] INFO JdbcUtil –员工[name = Jack,id = 103,departmentId = 2,薪金= 1400] 2013-01-03 02:47:34,313 31 [main] INFO JdbcUtil –大小:7,员工列表:[员工[name =杰克,id = 103,departmentId = 2,薪水= 1400],员工[name = John,id = 104,departmentId = 2,salary = 1450],员工[name = Johnny,id = 105,departmentId = 3,salary = 1050],员工[name = Alan,id = 108,departmentId = 3,salary = 1150],员工[name = Virat,id = 106 ,departmentId = 4,薪水= 850],员工[name = Vina,id = 107,departmentId = 4,薪水= 700],员工[name = joya,id = 109,departmentId = 4,薪水= 700]] 2013- 01-03 02:47:34,407 125 [main] INFO JdbcUtil –使用JdbcTemplate插入的行数:1 2013-01-03 02:47:34,423 141 [main] INFO JdbcUtil –用JdbcTemplated更新的行数:0 2013- 01-03 02:47:34,516 234
[main] INFO JdbcUtil –使用JdbcTemplate删除的行数:1
关于Spring框架的JdbcTemplate的要点
在Java应用程序中使用Spring框架的JdbcTemplate时要注意的几点:
1) JdbcTempalte
一旦配置,便是线程安全的,这意味着配置后,您可以在多个DAO类之间共享相同的JdbcTempalte
。
2) JdbcTemplate
类维护对DataSource的引用以与数据库进行通信。
关于如何在Spring框架中使用JdbcTemplate类完成与JDBC相关的任务的全部内容。 JdbcTemplate大大减少了执行各种JDBC任务(如执行查询)所需的编码,您无需创建PreparedStatement,Connection,也不必担心在finally块中关闭它们。
Spring框架负责所有样板工作,例如关闭连接,语句和结果集。 通过JdbcTemplate类中可用的各种重载方法,您可以执行所需的任何操作。 Use或Generics和variable参数使它在Spring 3.0中更加方便。
感谢您到目前为止阅读本文。 如果您找到此Spring JDBC教程,请与您的朋友和同事分享。 如果您有任何疑问或反馈,请留言。
翻译自: https://www.javacodegeeks.com/2020/07/10-jdbctemplate-examples-in-spring-framework.html
jdbctemplate