我正在研究如何在Spring Framework中使用JDBC对数据库执行查询 .
我正在学习本教程:http://www.tutorialspoint.com/spring/spring_jdbc_example.htm
在本教程中,我定义了一个 StudentDAO 接口,它只定义了我想要的CRUD方法 .
然后定义 Student 类,它是我想要在Student数据库表上保留的实体 .
然后定义 StudentMapper 类,它是 RowMapper 接口的特定实现,在这种情况下,用于将 ResultSet (由查询返回)中的特定记录映射到 Student 对象 .
然后我有了 StudentJDBCTemplate ,它支持我的 StudentDAO 接口的实现,在这个类中我实现了接口中定义的CRUD方法 .
好的,现在我怀疑 StudentMapper 类是如何工作的:在这个 StudentJDBCTemplate 类中定义了返回Student数据库表中所有记录列表的方法,这个:
public List<Student> listStudents() {
String SQL = "select * from Student";
List <Student> students = jdbcTemplateObject.query(SQL,
new StudentMapper());
return students;
}
你怎么看,这个方法返回一个List of Student对象并按以下方式工作:
它首先要做的是在SQL字符串中定义 return all record in the Student database table 的查询 .
然后通过jdbcTemplateObject对象上的查询方法调用执行此查询(即 JdbcTemplate Spring类**的istance)
此方法有两个参数:SQL String(包含必须执行的SQL查询)和一个新的 StudentMapper 对象,它接受查询返回的 ResultSet 对象并将其记录映射到新的Student对象上
在这里阅读:http://static.springsource.org/spring/docs/current/javadoc-api/org/springframework/jdbc/core/JdbcTemplate.html说: Execute a query given static SQL, mapping each row to a Java object via a RowMapper.
我的怀疑是因为我的 StudentMapper 使用 mapRow() 方法在Student对象上映射ResultSet记录,这是代码:
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自动调用的吗? (因为在这个例子中永远不会手动调用...)
TNX
安德里亚
然后,此查询由jdbcTemplateObject对象上的查询方法调用执行(即 JdbcTemplate Spring类**的istance)
4 回答
将
RowMapper
的实例传递给JdbcTemplate
方法时JdbcTemplate
取决于您调用的方法,将在内部使用映射器以及从JDBC连接获取的结果集,以创建所请求类型的对象 . 例如,由于您调用了JdbcTemplate#query(String, RowMapper)
,该方法将使用您的String SQL查询数据库,并将循环遍历ResultSet
中的每个"row",如下所示:因此,
Spring
的JdbcTemplate
方法将使用您提供的RowMapper
并调用其mapRow
方法来创建预期的返回对象 .您可能希望看看Martin Fowler的Data Mapper与Table Data Gateway一起了解这些事物是如何分布并提供low coupling的 .
这是我与BeanPropertyRowMapper一起使用的典型模式 . 它节省了大量的编码 . 您的查询需要对每列进行别名以匹配类中的属性名称 . 在这种情况下,
species_name as species
和其他列名称恰好匹配 .另一种方法是在每行需要更多自定义时使用RowMapper(此示例仅使用匿名类):
在Spring中使用RowMapper
这是由spring框架自动调用的 . 所有你需要的是指定