有关Spring Framework应用程序中JDBC在RowMapper中使用的一些疑问
问题内容:
我正在研究如何在Spring Framework中使用JDBC在数据库上执行查询。
我正在关注本教程:http
:
//www.tutorialspoint.com/spring/spring_jdbc_example.htm
在本教程中,我定义了 StudentDAO 接口,该接口仅定义了我想要的CRUD方法。
然后定义 Student 类,该类是我要保留在Student数据库表上的实体。
然后定义 StudentMapper 类,该类是 RowMapper 接口的特定实现,在这种情况下,该类用于将 ResultSet中
的特定记录(由查询返回)映射到 Student 对象。
然后,我有 StudentJDBCTemplate 是rappresent我实施 StudentDAO
界面,在这个类我实现的接口中定义的CRUD方法。
好了,现在我有一个关于如何疑问 StudentMapper 类的工作:在这个 StudentJDBCTemplate
类有定义的返回是在学生数据库表中,这一个所有记录的列表的方法:
public List<Student> listStudents() {
String SQL = "select * from Student";
List <Student> students = jdbcTemplateObject.query(SQL,
new StudentMapper());
return students;
}
可以看到,此方法返回Student对象的List并以以下方式工作:
它要做的第一件事是定义查询,该查询 返回 SQL String中 Student数据库表 中的 所有记录 。
然后,通过对jdbcTemplateObject对象的查询方法调用执行此查询(这是 JdbcTemplate Spring类的一个实例**
此方法采用两个参数:SQL字符串(包含必须执行的SQL查询)和新的 StudentMapper 对象,该对象采用查询返回的
ResultSet 对象并将其记录映射到新的Student对象上
在这里阅读:http :
//static.springsource.org/spring/docs/current/javadoc-
api/org/springframework/jdbc/core/JdbcTemplate.html这样说:
给定静态SQL执行查询,将每一行映射到Java对象通过RowMapper。
我怀疑我是相关的事实 StudentMapper 映射使用一个Student对象上一个ResultSet记录 mapRow()
方法,这是代码:
package com.tutorialspoint;
import java.sql.ResultSet;
import java.sql.SQLException;
import org.springframework.jdbc.core.RowMapper;
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;
}
}
那么,谁调用此 mapRow 方法?是由Spring Framework自动调用的吗?(因为在此示例中从不手动调用…)
特纳克斯
安德里亚
然后,通过对jdbcTemplateObject对象的查询方法调用执行此查询(这是 JdbcTemplate Spring类的一个实例**
问题答案:
当您将实例传递RowMapper
给JdbcTemplate
方法时
List <Student> students = jdbcTemplateObject.query(SQL, new StudentMapper());
JdbcTemplate
根据调用的方法的不同,将在内部使用映射器及其从JDBC连接获取的结果集来创建所需类型的对象。例如,自从您调用以来JdbcTemplate#query(String, RowMapper)
,该方法将使用您的String SQL查询数据库,并以这种方式遍历每个“行” ResultSet
:
ResultSet rs = ... // execute query
List<Student> students = ...// some list
int rowNum = 0;
while(rs.next()) {
Student student = rowMapper.mapRow(rs, rowNum);
students.add(student);
rowNum++;
}
return students;
因此,Spring
的JdbcTemplate
方法将使用RowMapper
您提供的并调用其mapRow
方法来创建预期的返回对象。
您可能希望结合使用Martin Fowler的Data
Mapper
和Table Data
Gateway来了解如何分配这些东西并提供低耦合。