Spring – NamedParameterJdbcTemplate
Java数据库连接 (JDBC API) 提供来自任何数据源(包括关系数据库、电子表格和平面文件)的通用数据访问。 JdbcTemplate是最基本和最经典的数据访问方法。 NamedParameterJdbcTemplate包装了 JdbcTemplate 并允许使用命名参数而不是传统的JDBC '?'占位符。
例子
在这个例子中,我们将使用命名参数将学生数据(id、name、department)插入到我们的数据源中。 NamedParameterJdbcTemplate 有几个方法,我们将在这个例子中使用 execute() 方法。
NamedParameterJdbcTemplate 的 execute() 方法的语法:
pubic T execute(String sql, Map map, PreparedStatementCallback psc)
对于本教程,我们将为 Student 表使用以下模式。
Student(id INT, name VARCHAR(45), department VARCHAR(45))
分步实施
第 1 步:创建表
在这一步中,我们将创建一个学生表来存储学生的信息。对于本教程,我们将假设您已在数据库中创建了下表。
CREATE TABLE STUDENT(
id INT,
name VARCHAR(45),
department VARCHAR(45));
第 2 步:添加依赖项
在这一步中,我们会将 maven 依赖项添加到我们的应用程序中。将以下依赖项添加到您的 pom.xml
XML
org.springframework
spring-jdbc
5.3.16
org.springframework
spring-context
5.0.8.RELEASE
mysql
mysql-connector-java
5.1.44
Java
public class Student {
// member variables
private int id;
private String name;
private String department;
public Student() {}
// parameterized constructor
public Student(int id, String name, String department) {
super();
this.id = id;
this.name = name;
this.department = department;
}
// getters and setters method
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getDepartment() {
return department;
}
public void setDepartment(String department) {
this.department = department;
}
// toString() method
@Override
public String toString() {
return "Student [id=" + id + ", name=" + name + ", department=" + department + "]";
}
}
Java
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.Map;
import org.springframework.dao.DataAccessException;
import org.springframework.jdbc.core.PreparedStatementCallback;
import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate;
import com.geeksforgeeks.model.Student;
public class StudentDao{
// Defining NamedParameterJdbcTemplate as member variable in order
// to use the execute() method of the NamedParameterJdbcTemplate's class
private NamedParameterJdbcTemplate namedParameterJdbcTemplate;
// Constructor
public StudentDao(NamedParameterJdbcTemplate namedParameterJdbcTemplate) {
this.namedParameterJdbcTemplate = namedParameterJdbcTemplate;
}
// User defined method to insert query data in data source
public void insertStudentInfo(Student student) {
String sqlQuery = "INSERT INTO student VALUES(:id, :name, :department)";
Map map = new HashMap();
map.put("id", student.getId());
map.put("name", student.getName());
map.put("department", student.getDepartment());
namedParameterJdbcTemplate.execute(sqlQuery, map, new PreparedStatementCallback() {
public Object doInPreparedStatement(PreparedStatement ps) throws SQLException, DataAccessException {
return ps.executeUpdate();
}
});
}
}
XML
Java
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.xml.XmlBeanFactory;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
import com.geeksforgeeks.dao.StudentDao;
import com.geeksforgeeks.model.Student;
public class TestNamedParameterJdbcTemplate {
public static void main(String[] agrs) {
// Reading the application-context file using
// class path of spring context xml file
Resource resource = new ClassPathResource("application-context.xml");
BeanFactory factory = new XmlBeanFactory(resource);
// Spring check the blueprint for studentDao bean
// from application-context.xml file and return it
StudentDao studentDao = (StudentDao)factory.getBean("studentDao");
Student studentObj = new Student(1, "geek", "computer science department");
studentDao.insertStudentInfo(studentObj);
System.out.println(studentObj);
}
}
第三步:创建模型类
现在,我们将为我们的学生创建一个模型班。此类将具有三个成员变量 id、name 和部门。我们还将定义它的 getter 和 setter 方法以及 toString() 方法和构造函数。
Java
public class Student {
// member variables
private int id;
private String name;
private String department;
public Student() {}
// parameterized constructor
public Student(int id, String name, String department) {
super();
this.id = id;
this.name = name;
this.department = department;
}
// getters and setters method
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getDepartment() {
return department;
}
public void setDepartment(String department) {
this.department = department;
}
// toString() method
@Override
public String toString() {
return "Student [id=" + id + ", name=" + name + ", department=" + department + "]";
}
}
第 4 步:创建 StudentDao 类
在这一步中,我们将创建一个StudentDao类并定义insertStudentInfo()方法并提供其定义以在我们的数据源中插入数据。
Java
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.Map;
import org.springframework.dao.DataAccessException;
import org.springframework.jdbc.core.PreparedStatementCallback;
import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate;
import com.geeksforgeeks.model.Student;
public class StudentDao{
// Defining NamedParameterJdbcTemplate as member variable in order
// to use the execute() method of the NamedParameterJdbcTemplate's class
private NamedParameterJdbcTemplate namedParameterJdbcTemplate;
// Constructor
public StudentDao(NamedParameterJdbcTemplate namedParameterJdbcTemplate) {
this.namedParameterJdbcTemplate = namedParameterJdbcTemplate;
}
// User defined method to insert query data in data source
public void insertStudentInfo(Student student) {
String sqlQuery = "INSERT INTO student VALUES(:id, :name, :department)";
Map map = new HashMap();
map.put("id", student.getId());
map.put("name", student.getName());
map.put("department", student.getDepartment());
namedParameterJdbcTemplate.execute(sqlQuery, map, new PreparedStatementCallback() {
public Object doInPreparedStatement(PreparedStatement ps) throws SQLException, DataAccessException {
return ps.executeUpdate();
}
});
}
}
第 5 步:Bean 配置
在这一步中,我们将创建 spring 配置文件并将其命名为application-contex.xml 。我们将配置我们的 bean 并使用 factory-method 属性来创建 bean。为了与数据库建立连接,我们需要以下信息用户名、密码、数据库连接、URL 和驱动程序类名称。所有这些信息都包含在DriverManagerDataSource类中,它具有返回Java类型连接的getConnection()方法。我们在 StudentDao 类中使用NamedParameterJdbcTemplate的实例,并使用构造函数注入方法传递它。
Note: In application-context, you need to define the whole path of your dao class
第 6 步:创建实用程序类
现在,我们将创建一个 Utility 类来测试我们的应用程序。为此创建一个新类并将其命名为TestNamedParameterJdbcTemplate。 Java并将以下代码添加到其中。
Java
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.xml.XmlBeanFactory;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
import com.geeksforgeeks.dao.StudentDao;
import com.geeksforgeeks.model.Student;
public class TestNamedParameterJdbcTemplate {
public static void main(String[] agrs) {
// Reading the application-context file using
// class path of spring context xml file
Resource resource = new ClassPathResource("application-context.xml");
BeanFactory factory = new XmlBeanFactory(resource);
// Spring check the blueprint for studentDao bean
// from application-context.xml file and return it
StudentDao studentDao = (StudentDao)factory.getBean("studentDao");
Student studentObj = new Student(1, "geek", "computer science department");
studentDao.insertStudentInfo(studentObj);
System.out.println(studentObj);
}
}
第 7 步:输出
现在,我们将运行我们的应用程序