Spring JDBC RowMapper接口示例
JdbcTemplate类使用org.springframework.jdbc.core.RowMapper <T>接口在每行的基础上映射ResultSet的行。该接口的实现执行将每行映射到结果对象的实际工作。如果抛出SQLExceptions将被调用的JdbcTemplate捕获和处理。
接口的声明
以下是org.springframework.jdbc.core.RowMapper<T>接口的声明 -
public interface RowMapper<T>
用法
步骤1 - 使用配置的数据源创建一个JdbcTemplate对象。
步骤2 - 创建一个实现RowMapper接口的StudentMapper对象。
步骤3 - 使用JdbcTemplate对象方法在使用StudentMapper对象时进行数据库操作。
实例
以下示例将演示如何使用spring jdbc进行读取查询。使用StudentMapper对象将读取记录从student表映射到Student对象。
语法
String SQL = "select * from Student";
List <Student> students = jdbcTemplateObject.query(SQL,
new StudentMapper());
在上面示例(语法)代码中 -
- SQL - 选择查询语句来来读取学生记录信息。
- jdbcTemplateObject -
StudentJDBCTemplate对象从数据库中读取Student对象。 - StudentMapper -
StudentMapper对象将学生记录映射到Student对象。
实例项目
要了解上述与Spring JDBC相关的概念,下面我们编写一个使用Mapper对象来读取查询并映射结果到Student对象。打开Eclipse IDE,并按照以下步骤创建一个Spring应用程序,这里创建一个名称为:RowMapper 的项目。
步骤说明
- 参考第一个Spring JDBC项目来创建一个Maven项目 - http://www.yiibai.com/springjdbc/first_application.html
- 更新bean配置并运行应用程序。
完整的项目结构如下所示 -

以下是Maven配置文件:pom.xml的代码内容:
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.yiibai</groupId>
<artifactId>RowMapper</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>jar</packaging>
<name>RowMapper</name>
<url>http://maven.apache.org</url>
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>3.8.1</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.40</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>4.1.0.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>4.1.4.RELEASE</version>
</dependency>
</dependencies>
</project>
以下是数据访问对象接口文件:StudentDAO.java的内容:
package com.yiibai;
import java.util.List;
import javax.sql.DataSource;
public interface StudentDAO {
/**
* This is the method to be used to initialize database resources ie.
* connection.
*/
public void setDataSource(DataSource ds);
/**
* This is the method to be used to list down all the records from the
* Student table.
*/
public List<Student> listStudents();
public Student getStudent(Integer id);
public void create(String name, Integer age);
}
以下是文件:Student.java的代码内容:
package com.yiibai;
public class Student {
private Integer age;
private String name;
private Integer id;
public void setAge(Integer age) {
this.age = age;
}
public Integer getAge() {
return age;
}
public void setName(String name) {
this.name = name;
}
public String getName() {
return name;
}
public void setId(Integer id) {
this.id = id;
}
public Integer getId() {
return id;
}
}
以下是文件:StudentMapper.java的代码内容:
package com.yiibai;
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;
}
}
实现类StudentJDBCTemplate.java实现了定义的DAO接口 - StudentDAO.java,以下是文件:StudentJDBCTemplate.java的代码内容:
package com.yiibai;
import java.util.List;
import java.util.ArrayList;
import javax.sql.DataSource;
import org.springframework.dao.DataAccessException;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.PreparedStatementSetter;
import org.springframework.jdbc.core.ResultSetExtractor;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
public class StudentJDBCTemplate implements StudentDAO {
private DataSource dataSource;
private JdbcTemplate jdbcTemplateObject;
public void setDataSource(DataSource dataSource) {
this.dataSource = dataSource;
this.jdbcTemplateObject = new JdbcTemplate(dataSource);
}
public List<Student> listStudents() {
String SQL = "select * from Student";
List<Student> students = jdbcTemplateObject.query(SQL, new StudentMapper());
return students;
}
public void create(String name, Integer age) {
// TODO Auto-generated method stub
String insertQuery = "insert into student (name, age) values (?, ?)";
jdbcTemplateObject.update(insertQuery, name, age);
System.out.println("Created Record Name = " + name + " Age = " + age);
return;
}
public Student getStudent(final Integer id) {
final String SQL = "select * from Student where id = ? ";
List<Student> students = jdbcTemplateObject.query(SQL, new PreparedStatementSetter() {
public void setValues(PreparedStatement preparedStatement) throws SQLException {
preparedStatement.setInt(1, id);
}
}, new StudentMapper());
return students.get(0);
}
}
以下是文件:MainApp.java的代码内容:
package com.yiibai;
import java.util.ArrayList;
import java.util.List;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import com.yiibai.StudentJDBCTemplate;
public class MainApp {
public static void main(String[] args) {
ApplicationContext context = new ClassPathXmlApplicationContext("application-beans.xml");
StudentJDBCTemplate studentJDBCTemplate = (StudentJDBCTemplate) context.getBean("studentJDBCTemplate");
System.out.println("------Records Creation--------");
studentJDBCTemplate.create("Maxsu", 21);
studentJDBCTemplate.create("Curry", 22);
studentJDBCTemplate.create("Suzend", 23);
System.out.println("------Listing Multiple Records--------");
List<Student> students = studentJDBCTemplate.listStudents();
for (Student record : students) {
System.out.print("ID : " + record.getId());
System.out.print(", Name : " + record.getName());
System.out.println(", Age : " + record.getAge());
}
}
}
以下是文件:application-beans.xml的代码内容:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd ">
<!-- Initialization for data source -->
<bean id="dataSource"
class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="com.mysql.jdbc.Driver" />
<property name="url" value="jdbc:mysql://localhost:3306/test?characterEncoding=utf8&useSSL=true" />
<property name="username" value="root" />
<property name="password" value="123456" />
</bean>
<!-- Definition for studentJDBCTemplate bean -->
<bean id="studentJDBCTemplate" class="com.yiibai.StudentJDBCTemplate">
<property name="dataSource" ref="dataSource" />
</bean>
</beans>
注意: application-beans.xml 文件的位置是:{workspace}/fistapp/src/main/java 目录,如果放置错了,程序可能会因为找不到此配置文件而出错。
完成创建源代码和bean和数据库连接信息的文件配置后,运行应用程序。这里先简单说明一下运行的步骤,在项目名称(RowMapper)上点击右键,在弹出的菜单中选择:【Run As】-> 【Maven test】
在运行测试成功后,应该会输出类似以下内容(含有 BUILD SUCCESS 的信息) 。
接下来,点击类文件:MainApp.java 选择【Run As】->【Java Application】,如果应用程序一切正常,这将打印以下结果:
------Records Creation--------
Created Record Name = Maxsu Age = 21
Created Record Name = Curry Age = 22
Created Record Name = Suzend Age = 23
------Listing Multiple Records--------
ID : 1, Name : Maxsu, Age : 21
ID : 2, Name : Curry, Age : 22
ID : 3, Name : Suzend, Age : 23
Spring JDBC RowMapper接口示例的更多相关文章
- Spring JDBC ResultSetExtractor接口示例
org.springframework.jdbc.core.ResultSetExtractor接口是JdbcTemplate的查询方法使用的回调接口.此接口的实现执行从ResultSet提取结果的实 ...
- Spring JDBC PreparedStatementSetter接口示例
org.springframework.jdbc.core.PreparedStatementSetter接口充当JdbcTemplate类使用的一般回调接口.该接口在JdbcTemplate类提供的 ...
- Spring JDBC SqlUpdate类示例
org.springframework.jdbc.object.SqlUpdate类提供了表示SQL更新的可重用操作对象. 使用到的 Student 表的结构如下 - CREATE TABLE Stu ...
- Spring JDBC StoredProcedure类示例
org.springframework.jdbc.core.StoredProcedure类是RDBMS存储过程的对象抽象的超类.这个类是抽象的,目的是让子类将提供一个用于调用的类型化方法,该方法委托 ...
- Spring JDBC SqlQuery类示例
org.springframework.jdbc.object.SqlQuery类提供了表示SQL查询的可重用操作对象. 使用到的 Student 表的结构如下 - CREATE TABLE Stud ...
- Spring JDBC SimpleJdbcCall类示例
org.springframework.jdbc.core.SimpleJdbcCall类是表示对存储过程或存储函数的调用的多线程,可重用的对象. 它提供元数据处理以简化访问基本存储过程/函数所需的代 ...
- Spring JDBC SimpleJdbcInsert类示例
org.springframework.jdbc.core.SimpleJdbcInsert类是一个多线程,可重用的对象,为将数据插入表提供了易用的功能.它提供元数据处理以简化构建基本insert语句 ...
- Spring JDBC JdbcTemplate类示例
org.springframework.jdbc.core.JdbcTemplate类是JDBC核心包中的中心类.它简化了JDBC的使用,并有助于避免常见的错误. 它执行核心JDBC工作流,留下应用程 ...
- Spring JDBC常用方法详细示例
Spring JDBC使用简单,代码简洁明了,非常适合快速开发的小型项目.下面对开发中常用的增删改查等方法逐一示例说明使用方法 1 环境准备 启动MySQL, 创建一个名为test的数据库 创建Mav ...
随机推荐
- [SQL in Azure] Windows Azure Virtual Machine Readiness and Capacity Assessment
http://technet.microsoft.com/en-us/solutionaccelerators/dd537566.aspx http://blogs.technet.com/b/map ...
- [Windows Azure] How to Manage Cloud Services
How to Manage Cloud Services To use this feature and other new Windows Azure capabilities, sign up f ...
- 【MySQL】MySQL层级数据的递归遍历
层级的业务数据在系统中很常见,如组织机构.商品品类等. 如果要获取层级数据的全路径,除了缓存起来,就是递归访问的方式了: 将层级数据缓存在redis中,用redis递归获取层级结构.此方法效率高. 在 ...
- 【Linux技术】BusyBox详解
BusyBox 是很多标准 Linux® 工具的一个单个可执行实现.BusyBox 包含了一些简单的工具,例如 cat 和 echo,还包含了一些更大.更复杂的工具,例如 grep.find.moun ...
- 【内核】linux2.6版本内核编译配置选项(二)
目录 Linux2.6版本内核编译配置选项(一):http://infohacker.blog.51cto.com/6751239/1203633 Linux2.6版本内核编译配置选项(二):http ...
- IntelliJ IDEA中的properties文件乱码转成中文[unicode码转中文]
在IntelliJ IDEA中,一些.properties后缀的配置文件中的中文常常会是下面的样子,看不懂怎么办? 解决办法:File-->Settings-->File Encoding ...
- JS操作MongoDB
JavaScript处理MongoDB,更新数据: #!/bin/bash mongo=/home/zhangzhenghai/cluster/mongodb/bin/mongo if true; t ...
- 在Windows上弄一个redis的docker容器
[本文出自天外归云的博客园] Docker核心概念简介 镜像是一个面向docker引擎的只读模板,包含了文件系统. 镜像是创建容器的基础,容器类似于一个沙箱,用来运行和隔离应用. 容器是从镜像创建的应 ...
- [转]Oracle 语法之 OVER (PARTITION BY ..) 及开窗函数
oracle的分析函数over 及开窗函数 一:分析函数Oracle从8.1.6开始提供分析函数,分析函数用于计算基于组的某种聚合值,它和聚合函数的不同之处是 对于每个组返回多行,而聚合函数对于每个组 ...
- [deb]制作deb包
转自:http://www.cnblogs.com/Genesis-007/p/5219960.html 查看系统安装了哪些deb包: dpkg -l 打包: dpkg -b dir result.d ...