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 ...
随机推荐
- 每日英语:U.S. Media Firms Stymied in China
China's recent clampdown on foreign media is crimping the expansion plans of Western news organizati ...
- python(49):把文件压缩成zip格式的文件
有时需要用到压缩文件,网上搜集了一段代码: 分享一下: import os import zipfile def make_zip(localPath, pname): zipf = zipfile. ...
- http.ResponseWriter的Flush
func handle(res http.ResponseWriter, req *http.Request) { fmt.Fprintf(res, "sending first line ...
- 监听的instance status blocked分析
对于处于NOMOUNT状态的数据库,PMON还没有将服务注册到监听上,这个时候服务的状态是BLOCKED的,对于来自远程的任何连接都会报ORA-12528错误.如下: [oracle@dbtest ~ ...
- Python3.5爬取豆瓣电视剧数据并且同步到mysql中
#!/usr/local/bin/python # -*- coding: utf-8 -*- # Python: 3.5 # Author: zhenghai.zhang@xxx.com # Pro ...
- 【Bootstrap Method】Evaluating The Accuracy of a Classifier
自助法介绍: 非参数统计中一种重要的估计统计量方差进而进行区间估计的统计方法,也称为自助法.其核心思想和基本步骤如下:(1)采用重抽样技术从原始样本中抽取一定数量(自己给定)的样本,此过程允许重复抽样 ...
- maven deploy distributionManagement
分发构件至远程仓库 mvn install 会将项目生成的构件安装到本地Maven仓库,mvn deploy 用来将项目生成的构件分发到远程Maven仓库.本地Maven仓库的构件只能供当前用户使用, ...
- mysql 添加外键时 error 150 问题总汇
当你试图在mysql中创建一个外键的时候,这个出错会经常发生,这是非常令人沮丧的.像这种不能创建一个.frm 文件的报错好像暗示着操作系统的文件的权限错误或者其它原因,但实际上,这些都不是的,事实上, ...
- Python学习笔记(4):容器、迭代对象、迭代器、生成器、生成器表达式
在了解Python的数据结构时,容器(container).可迭代对象(iterable).迭代器(iterator).生成器(generator).列表/集合/字典推导式(list,set,dict ...
- Mysql 多表查询详解
Reference: https://blog.csdn.net/jintao_ma/article/details/51260458 一.前言 二.示例 三.注意事项 一.前言 上篇讲到Mysql ...