1. JdbcDaoSupport
public abstract class JdbcDaoSupport extends DaoSupport { private JdbcTemplate jdbcTemplate; public final void setDataSource(DataSource dataSource) { if (this.jdbcTemplate == null || dataSource != this.jdbcTemplate.getDataSource()) { this.jdbcTemplate = createJdbcTemplate(dataSource); initTemplateConfig(); } } public final JdbcTemplate getJdbcTemplate() { return this.jdbcTemplate; } }
As we can see from the source code that DaoSupport simply added a JdbcTemplate property.
And when we extends JdbcDaoSupport, we don't need to write the redundancy code of setDataSource().
When we need get jdbcTemplate, we simply call getJdbcTemplate() method.
package edu.xmu.jdbc.dao; import org.springframework.jdbc.core.JdbcTemplate; import org.springframework.jdbc.core.support.JdbcDaoSupport; import edu.xmu.jdbc.bean.Student; public class JdbcSupportDao extends JdbcDaoSupport { public void createStudent(Student student) { String sql = "insert into student(name, age) value(?, ?)"; JdbcTemplate jdbcTemplate = getJdbcTemplate(); jdbcTemplate.update(sql, student.getName(), student.getAge()); } }
2. NamedParameterDaoSupport
public class NamedParameterJdbcDaoSupport extends JdbcDaoSupport { private NamedParameterJdbcTemplate namedParameterJdbcTemplate; public NamedParameterJdbcTemplate getNamedParameterJdbcTemplate() { return namedParameterJdbcTemplate; } }
As we can see, when our dao need NamedParameterJdbcTemplate instead of JdbcTemplate,
we can extends NamedParameterDaoSupport.
3. NamedParameterJdbcTemplate
When we execute preparedStatements, we need to use ? as place holder.
But NamedParameterJdbcTemplate offers a mechanism that we can use specific name as holder.
package edu.xmu.jdbc.dao; import java.sql.ResultSet; import java.sql.SQLException; import java.util.HashMap; import java.util.Map; import org.springframework.jdbc.core.RowMapper; import org.springframework.jdbc.core.namedparam.BeanPropertySqlParameterSource; import org.springframework.jdbc.core.namedparam.MapSqlParameterSource; import org.springframework.jdbc.core.namedparam.NamedParameterJdbcDaoSupport; import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate; import org.springframework.jdbc.core.namedparam.SqlParameterSource; import edu.xmu.jdbc.bean.Student; public class NamedParameterJdbcTemplateDao extends NamedParameterJdbcDaoSupport { /** * In this method, we use MapSqlParameterSource for placeholder value * mapping * * @param student */ public void createStudent(Student student) { String sql = "insert into student(name, age) value(:name, :age)"; NamedParameterJdbcTemplate jdbcTemplate = getNamedParameterJdbcTemplate(); MapSqlParameterSource namedParameters = new MapSqlParameterSource( "name", student.getName()); namedParameters.addValue("age", student.getAge()); jdbcTemplate.update(sql, namedParameters); } /** * In this method, we use BeanPropertySqlParameterSource for placeholder * value mapping * * @param student */ public void createStudent2(Student student) { String sql = "insert into student(name, age) value(:name, :age)"; NamedParameterJdbcTemplate jdbcTemplate = getNamedParameterJdbcTemplate(); SqlParameterSource parameterSource = new BeanPropertySqlParameterSource( student); jdbcTemplate.update(sql, parameterSource); } /** * In this method, we use HashMap for placeholder value mapping * * @param student */ public void createStudent3(Student student) { String sql = "insert into student(name, age) value(:name, :age)"; NamedParameterJdbcTemplate jdbcTemplate = getNamedParameterJdbcTemplate(); Map<String, Object> map = new HashMap<String, Object>(); map.put("name", student.getName()); map.put("age", student.getAge()); jdbcTemplate.update(sql, map); } public Student retrieveStudent(int id) { String sql = "select id, name, age from student where id=:id"; NamedParameterJdbcTemplate jdbcTemplate = getNamedParameterJdbcTemplate(); SqlParameterSource parameters = new MapSqlParameterSource("id", id); return jdbcTemplate.queryForObject(sql, parameters, new RowMapper<Student>() { public Student mapRow(ResultSet rs, int rowNum) throws SQLException { int id = rs.getInt("id"); String name = rs.getString("name"); int age = rs.getInt("age"); return new Student(id, name, age); } }); } public void clearTable() { String sql = "truncate table student"; getJdbcTemplate().execute(sql); } }
package edu.xmu.jdbc.dao; import org.junit.After; import org.junit.Before; import org.junit.Test; import org.springframework.jdbc.datasource.DriverManagerDataSource; import edu.xmu.jdbc.bean.Student; public class NamedParameterJdbcTemplateDaoTest { private DriverManagerDataSource dataSource; private String url = "jdbc:mysql://localhost:3306/jdbctest"; private String username = "root"; private String password = "root"; private NamedParameterJdbcTemplateDao dao; @Before public void setUp() { dataSource = new DriverManagerDataSource(url, username, password); dataSource.setDriverClassName("com.mysql.jdbc.Driver"); dao = new NamedParameterJdbcTemplateDao(); dao.setDataSource(dataSource); } @Test public void createStudentTest() { Student student = new Student("Davy", 24); dao.createStudent(student); Student returnStudent = dao.retrieveStudent(1); System.out.println(returnStudent); } @Test public void createStudent2Test() { Student student = new Student("Davy", 24); dao.createStudent2(student); Student returnStudent = dao.retrieveStudent(1); System.out.println(returnStudent); } @Test public void createStudent3Test() { Student student = new Student("Davy", 24); dao.createStudent3(student); Student returnStudent = dao.retrieveStudent(1); System.out.println(returnStudent); } @After public void tearDown() { dao.clearTable(); } }
There are three approaches by which we can substitute placeholdes.
1> Use MapSqlParameterSource
2> Use BeanPropertySqlParameterSource
3> Use simple Map
4. SimpleJdbcTemplate --> Depreciated
1> Enables uncertain query parameters with the technology provided since Java 1.5.
But this function has been added to JdbcTemplate as well.
2> Enables named placeholder, which is the main function of NamedParameterJdbcTemplate.
3> This class is now depreciated as all its function provided are also provided by other classes.
/** * @deprecated since Spring 3.1 in favor of {@link org.springframework.jdbc.core.JdbcTemplate} and * {@link org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate}. The JdbcTemplate and * NamedParameterJdbcTemplate now provide all the functionality of the SimpleJdbcTemplate. */ @Deprecated public class SimpleJdbcTemplate implements SimpleJdbcOperations{ ... }
5. Retrieve auto-generated keys
1) When we use auto-generated policy in db primary key generation,
after we execute CUD operation, we need to get the new ID.
That would be redundancy if we execute a query after that.
2) Spring JDBC offers a class KeyHolder for this special purpose.
1> Method in JdbcTemplate
public int update(final PreparedStatementCreator psc, final KeyHolder generatedKeyHolder);
2> Method in NamedParameterJdbcTemplate
public int update(String sql, SqlParameterSource paramSource, KeyHolder generatedKeyHolder); public int update(String sql, SqlParameterSource paramSource, KeyHolder generatedKeyHolder, String[] keyColumnNames);
Example for JdbcTemplate:
package edu.xmu.jdbc.dao; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.SQLException; import org.springframework.jdbc.core.JdbcTemplate; import org.springframework.jdbc.core.PreparedStatementCreator; import org.springframework.jdbc.core.support.JdbcDaoSupport; import org.springframework.jdbc.support.GeneratedKeyHolder; import org.springframework.jdbc.support.KeyHolder; import edu.xmu.jdbc.bean.Student; public class JdbcTemplateKey extends JdbcDaoSupport { public int createStudent(final Student student) { final String sql = "insert into student(name, age) values(?, ?)"; JdbcTemplate jdbcTemplate = getJdbcTemplate(); KeyHolder keyHolder = new GeneratedKeyHolder(); jdbcTemplate.update(new PreparedStatementCreator() { public PreparedStatement createPreparedStatement(Connection con) throws SQLException { PreparedStatement ps = con.prepareStatement(sql, new String[] { "id" }); ps.setString(1, student.getName()); ps.setInt(2, student.getAge()); return ps; } }, keyHolder); return keyHolder.getKey().intValue(); } }
Example for NamedParameterJdbcTemplate
package edu.xmu.jdbc.dao; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.SQLException; import org.springframework.jdbc.core.JdbcTemplate; import org.springframework.jdbc.core.PreparedStatementCreator; import org.springframework.jdbc.core.namedparam.BeanPropertySqlParameterSource; import org.springframework.jdbc.core.namedparam.NamedParameterJdbcDaoSupport; import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate; import org.springframework.jdbc.core.namedparam.SqlParameterSource; import org.springframework.jdbc.support.GeneratedKeyHolder; import org.springframework.jdbc.support.KeyHolder; import edu.xmu.jdbc.bean.Student; public class NamedParameterJdbcTemplateKey extends NamedParameterJdbcDaoSupport { public int createStudent(final Student student) { final String sql = "insert into student(name, age) values(?, ?)"; JdbcTemplate jdbcTemplate = getJdbcTemplate(); KeyHolder keyHolder = new GeneratedKeyHolder(); jdbcTemplate.update(new PreparedStatementCreator() { public PreparedStatement createPreparedStatement(Connection con) throws SQLException { PreparedStatement ps = con.prepareStatement(sql, new String[] { "id" }); ps.setString(1, student.getName()); ps.setInt(2, student.getAge()); return ps; } }, keyHolder); return keyHolder.getKey().intValue(); } public int createStudent2(Student student) { String sql = "insert into student(name, age) values(:name, :age)"; NamedParameterJdbcTemplate jdbcTemplate = getNamedParameterJdbcTemplate(); KeyHolder keyHolder = new GeneratedKeyHolder(); SqlParameterSource paramSource = new BeanPropertySqlParameterSource( student); int rowCount = jdbcTemplate.update(sql, paramSource, keyHolder); System.out.println(rowCount + " row affected."); return keyHolder.getKey().intValue(); } public int createStudent3(Student student) { String sql = "insert into student(name, age) values(:name, :age)"; NamedParameterJdbcTemplate jdbcTemplate = getNamedParameterJdbcTemplate(); KeyHolder keyHolder = new GeneratedKeyHolder(); SqlParameterSource paramSource = new BeanPropertySqlParameterSource( student); int rowCount = jdbcTemplate.update(sql, paramSource, keyHolder, new String[] { "id" }); System.out.println(rowCount + " row affected."); return keyHolder.getKey().intValue(); } }
package edu.xmu.jdbc.dao; import org.junit.After; import org.junit.Before; import org.junit.Test; import org.springframework.jdbc.datasource.DriverManagerDataSource; import edu.xmu.jdbc.bean.Student; public class NamedParameterJdbcTemplateKeyTest { private DriverManagerDataSource dataSource; private String url = "jdbc:mysql://localhost:3306/jdbctest"; private String username = "root"; private String password = "root"; private NamedParameterJdbcTemplateKey dao; @Before public void setUp() { dataSource = new DriverManagerDataSource(url, username, password); dataSource.setDriverClassName("com.mysql.jdbc.Driver"); dao = new NamedParameterJdbcTemplateKey(); dao.setDataSource(dataSource); } @Test public void createStudentTest() { Student student = new Student("Davy", 24); int id = dao.createStudent(student); System.out.println("Generated id: " + id); } @Test public void createStudent2Test() { Student student = new Student("Davy", 24); int id = dao.createStudent2(student); System.out.println("Generated id: " + id); } @Test public void createStudent3Test() { Student student = new Student("Davy", 24); int id = dao.createStudent3(student); System.out.println("Generated id: " + id); } @After public void tearDown() { } }
相关推荐
1. **JdbcTemplate**:这是Spring JDBC的核心类,它通过模板方法模式将常见的JDBC操作进行了封装,如执行SQL查询、更新、调用存储过程等。开发者只需要关注SQL语句和参数,而无需处理连接创建、关闭、异常处理等繁琐...
1. **JdbcTemplate**:这是Spring JDBC的基础组件,它通过模板方法模式封装了常见的JDBC操作,如执行SQL查询、更新、存储过程等。使用JdbcTemplate,开发者无需手动管理数据库连接、预编译语句、结果集转换等细节,...
Spring JDBC通过提供JdbcTemplate和SimpleJdbcTemplate等工具类,帮助开发者以更安全、更易于管理的方式与数据库进行交互,降低了传统JDBC代码的复杂性。下面我们将详细探讨Spring JDBC的核心概念、工作原理以及如何...
Spring Data JDBC与JDBC是两种不同的数据库访问方式,它们在Java开发中有着广泛的应用。JDBC(Java Database Connectivity)是Java平台的标准API,用于与各种数据库进行交互。它提供了低级别的数据库操作,如建立...
本篇将深入探讨Spring JDBC的核心概念、使用方法以及它如何通过JdbcTemplate对象简化JDBC的开发。 首先,让我们了解Spring JDBC的基本理念。Spring JDBC的目标是减少传统JDBC代码的复杂性和易错性,通过提供一套...
总之,Spring JDBC 4.0.0版本的`JdbcTemplate`是Spring框架在数据库操作方面的重要工具,它的设计哲学是简化JDBC编程,提供更安全、更易用的API,以帮助开发者更高效地管理数据库操作。通过这个压缩包中的“spring-...
Spring JDBC模板类——`org.springframework.jdbc.core.JdbcTemplate`是Spring框架中的核心组件,它为Java开发者提供了一种方便、安全的方式来执行SQL语句,而无需直接管理数据库连接。`JdbcTemplate`通过抽象出低...
Spring JdbcTemplate的出现是为了弥补原生JDBC在编码上的繁琐,它通过模板方法模式,将SQL执行、结果集处理等进行了抽象,使得开发者可以更专注于业务逻辑,而无需过多关注数据库访问的细节。同时,它还提供了事务...
Spring JDBCTemplate是一个强大的工具,它是Spring框架的一部分,用于简化Java数据库连接(JDBC)操作。在本示例中,我们将深入探讨Spring JDBCTemplate的工作原理、优势以及如何在实际项目中进行配置和使用。 首先...
Spring Boot JDBC是Spring框架的一个重要组成部分,它简化了在Java应用程序中使用JDBC(Java Database Connectivity)进行数据库操作的方式。Spring Boot的设计理念是“约定优于配置”,因此它为开发者提供了开箱即...
JdbcTemplate是Spring框架提供的一种用于简化JDBC编程的对象。通过封装原生的JDBC API,JdbcTemplate不仅提高了代码的可读性和可维护性,还帮助开发者避免了许多常见的错误,比如资源关闭、SQL注入等问题。 Spring...
JdbcTemplate是Spring JDBC模块中的核心组件,它提供了一种模板化的JDBC操作方式,降低了数据库访问的复杂性,同时保持了良好的封装和异常处理机制。在使用Spring JDBC之前,我们需要确保引入了必要的jar包。这里...
`spring-jdbc-4.2.xsd`是Spring 4.2版本的JDBC配置XML Schema定义,它定义了一系列元素和属性,用来描述如何配置Spring的JdbcTemplate、NamedParameterJdbcTemplate、SimpleJdbcInsert等核心组件,以及事务管理相关...
Spring JDBC 提供了 JdbcTemplate 和 NamedParameterJdbcTemplate,这两个工具类极大地减少了我们处理数据库连接、事务管理、结果集映射等工作所需的手动编码。 首先,集成Spring JDBC需要引入相应的jar包。在现代...
在本实例中,我们将深入探讨Spring JDBC的使用,并以`SpringJdbcTemplate`为例来阐述其主要功能和优势。 首先,Spring JDBC通过`JdbcTemplate`和`NamedParameterJdbcTemplate`类提供了强大的数据库访问功能。`...
标题 "jdbcTemplate-spring对jdbc的支持" 涉及到的是Spring框架中的一个核心组件——JdbcTemplate,它是Spring对Java数据库连接(JDBC)的一种封装,用于简化数据库操作。JdbcTemplate提供了一种模板方法模式,使得...
基于spring jdbc的上层封装,底层jdbc操作基于JdbcTemplate,支持MySql、SqlServer、Oracle数据库,强弱类型完美结合 1、mini-jdbc:针对spring jdbc的一些不方便的地方,做了一些封装,大小写不敏感,简化了日常的...
Spring JDBC简化了数据库操作,例如,通过`JdbcTemplate`可以方便地执行SQL语句,进行增删改查操作。同时,Spring的事务管理功能(`PlatformTransactionManager`)可以确保在多条数据库操作之间保持事务的原子性。在...
Spring JDBC是Spring框架的一部分,它提供了一种抽象层,使得我们能够更方便地使用Java数据库连接(JDBC)技术。这个“SpringJDBC.rar”压缩包文件可能包含了关于如何在Spring框架中集成和使用JDBC的相关示例和教程...
Spring JDBC是Spring框架的一个重要模块,它为Java开发者提供了与关系数据库交互的抽象层,简化了JDBC(Java Database Connectivity)的使用。本教程通过一个实际案例,将深入讲解Spring JDBC的基本概念、核心组件...