spring(3) JDBC
Step | Description |
---|---|
1 | Create a project with a name SpringExample and create a package com.tutorialspoint under the src folder in the created project. |
2 | Add required Spring libraries using Add External JARs option as explained in the Spring Hello World Example chapter. |
3 | Add Spring JDBC specific latest libraries mysql-connector-java.jar, org.springframework.jdbc.jar and org.springframework.transaction.jar in the project. You can download required libraries if you do not have them already. |
4 | Create DAO interface StudentDAO and list down all the required methods. Though it is not required and you can directly write StudentJDBCTemplate class, but as a good practice, let's do it. |
5 | Create other required Java classes Student, StudentMapper, StudentJDBCTemplate and MainApp under the com.tutorialspoint package. |
6 | Make sure you already created Student table in TEST database. Also make sure your MySQL server is working fine and you have read/write access on the database using the give username and password. |
7 | Create Beans configuration file Beans.xml under the src folder. |
8 | The final step is to create the content of all the Java files and Bean Configuration file and run the application as explained below. |
上面介绍了怎样将JDBC与Spring进行整合的步骤,下面给出实例
Following is the content of the Data Access Object interface file StudentDAO.java:
package com.tutorialspoint; 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 create
* a record in the Student table.
*/
public void create(String name, Integer age);
/**
* This is the method to be used to list down
* a record from the Student table corresponding
* to a passed student id.
*/
public Student getStudent(Integer id);
/**
* This is the method to be used to list down
* all the records from the Student table.
*/
public List<Student> listStudents();
/**
* This is the method to be used to delete
* a record from the Student table corresponding
* to a passed student id.
*/
public void delete(Integer id);
/**
* This is the method to be used to update
* a record into the Student table.
*/
public void update(Integer id, Integer age);
}
Following is the content of the Student.java file:
package com.tutorialspoint; 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;
}
}
Following is the content of the StudentMapper.java file
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;
}
}
Following is the implementation class file StudentJDBCTemplate.java for the defined DAO interface StudentDAO:
package com.tutorialspoint; import java.util.List;
import javax.sql.DataSource;
import org.springframework.jdbc.core.JdbcTemplate; 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 void create(String name, Integer age) {
String SQL = "insert into Student (name, age) values (?, ?)"; jdbcTemplateObject.update( SQL, name, age);
System.out.println("Created Record Name = " + name + " Age = " + age);
return;
} public Student getStudent(Integer id) {
String SQL = "select * from Student where id = ?";
Student student = jdbcTemplateObject.queryForObject(SQL,
new Object[]{id}, new StudentMapper());
return student;
} public List<Student> listStudents() {
String SQL = "select * from Student";
List <Student> students = jdbcTemplateObject.query(SQL,
new StudentMapper());
return students;
} public void delete(Integer id){
String SQL = "delete from Student where id = ?";
jdbcTemplateObject.update(SQL, id);
System.out.println("Deleted Record with ID = " + id );
return;
} public void update(Integer id, Integer age){
String SQL = "update Student set age = ? where id = ?";
jdbcTemplateObject.update(SQL, age, id);
System.out.println("Updated Record with ID = " + id );
return;
} }
Following is the content of the MainApp.java file:
package com.tutorialspoint; import java.util.List; import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import com.tutorialspoint.StudentJDBCTemplate; public class MainApp {
public static void main(String[] args) {
ApplicationContext context =
new ClassPathXmlApplicationContext("Beans.xml"); StudentJDBCTemplate studentJDBCTemplate =
(StudentJDBCTemplate)context.getBean("studentJDBCTemplate"); System.out.println("------Records Creation--------" );
studentJDBCTemplate.create("Zara", 11);
studentJDBCTemplate.create("Nuha", 2);
studentJDBCTemplate.create("Ayan", 15); 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());
} System.out.println("----Updating Record with ID = 2 -----" );
studentJDBCTemplate.update(2, 20); System.out.println("----Listing Record with ID = 2 -----" );
Student student = studentJDBCTemplate.getStudent(2);
System.out.print("ID : " + student.getId() );
System.out.print(", Name : " + student.getName() );
System.out.println(", Age : " + student.getAge()); }
}
Following is the configuration file 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"/>
<property name="username" value="root"/>
<property name="password" value="password"/>
</bean> <!-- Definition for studentJDBCTemplate bean -->
<bean id="studentJDBCTemplate"
class="com.tutorialspoint.StudentJDBCTemplate">
<property name="dataSource" ref="dataSource" />
</bean> </beans>
其中的主要部分就是红色字体标注的部分。
另外,实现文中代码的表为
CREATE TABLE Student(
ID INT NOT NULL AUTO_INCREMENT,
NAME VARCHAR(20) NOT NULL,
AGE INT NOT NULL,
PRIMARY KEY (ID)
);
文章代码来自于:
http://www.tutorialspoint.com/spring/spring_jdbc_example.htm
spring(3) JDBC的更多相关文章
- Spring的JDBC框架
转自: http://www.cnblogs.com/windlaughing/p/3287750.html Spring JDBC提供了一套JDBC抽象框架,用于简化JDBC开发. Spring主要 ...
- [原创]java WEB学习笔记109:Spring学习---spring对JDBC的支持:使用 JdbcTemplate 查询数据库,简化 JDBC 模板查询,在 JDBC 模板中使用具名参数两种实现
本博客的目的:①总结自己的学习过程,相当于学习笔记 ②将自己的经验分享给大家,相互学习,互相交流,不可商用 内容难免出现问题,欢迎指正,交流,探讨,可以留言,也可以通过以下方式联系. 本人互联网技术爱 ...
- Spring整合jdbc
首先web.xml文件跟往常一样,加载spring容器和加载org.springframework.web.context.ContextLoaderListener读取applicationCont ...
- 【Spring】Spring系列4之Spring支持JDBC
4.Spring支持JDBC 4.1.使用JdbcTemplate简化JDBC开发 也可以这么用(不推荐): 4.2.使用NamedParameterJdbcTemplate
- Spring对jdbc的支持
Spring对jdbc技术提供了很好的支持. 体现在: 1)Spring对c3p连接池的支持很完善: 2)Spring对jdbc提供了JdbcTemplate,来简化jdbc操作: 1.使用步骤 1) ...
- Spring实战6:利用Spring和JDBC访问数据库
主要内容 定义Spring的数据访问支持 配置数据库资源 使用Spring提供的JDBC模板 写在前面:经过上一篇文章的学习,我们掌握了如何写web应用的控制器层,不过由于只定义了SpitterRep ...
- Spring对jdbc支持
4. Spring对jdbc支持 spring对jdbc提供了很好的支持 体现在: 1.Spring对C3P0连接池的支持很完善 2.Spring对jdbc提供了jdbcTemplate来简化jdbc ...
- JAVAEE——spring03:spring整合JDBC和aop事务
一.spring整合JDBC 1.spring提供了很多模板整合Dao技术 2.spring中提供了一个可以操作数据库的对象.对象封装了jdbc技术. JDBCTemplate => JDBC模 ...
- (转) Spring Boot JDBC 连接数据库
文本将对在Spring Boot构建的Web应用中,基于MYSQL数据库的几种数据库连接方式进行介绍. 包括JDBC.JPA.MyBatis.多数据源和事务. 1 JDBC 连接数据库 1.1 属性配 ...
- Spring第七篇【Spring的JDBC模块】
前言 上一篇Spring博文主要讲解了如何使用Spring来实现AOP编程,本博文主要讲解Spring的对JDBC的支持- 对于JDBC而言,我们肯定不会陌生,我们在初学的时候肯定写过非常非常多的JD ...
随机推荐
- FreeBSD_11-系统管理——{Part_0-基础}
Tips: sysctl -d kern.maxvnodes #查看系统控制选项的含义 true > file #清空文件内容 alias ls 'ls -I(大写i)' #取消 root 的 ...
- MongoDB介绍与windows下安装
MongoDB是一个介于关系数据库和非关系数据库之间的产品,是非关系数据库当中功能最丰富,最像关系数据库的.他支持的数据结构非常松散,是类 似json的bjson格式,因此可以存储比较复杂的数据类型. ...
- Reduce inversion count 求最小逆序数
本问题出自:微软2014实习生及秋令营技术类职位在线测试 (Microsoft Online Test for Core Technical Positions) Description Find a ...
- C#函数式编程之缓存技术
缓存技术 该节我们将分成两部分来讲解,第一部分为预计算,第二部分则为缓存.缓存这个技术对应从事开发的人员来说是非常熟悉的,从页面缓存到数据库缓存无处不在,而其最重要的特点就是在第一次查询后将数据缓存, ...
- HttpClient与APS.NET Web API:请求内容的压缩与解压
首先说明一下,这里的压缩与解压不是通常所说的http compression——那是响应内容在服务端压缩.在客户端解压,而这里是请求内容在客户端压缩.在服务端解压. 对于响应内容的压缩,一般Web服务 ...
- Windows上成功编译CoreCLR源代码
昨天得知微软在GitHub上发布CoreCLR的源代码之后,立马从GitHub上签出代码,并尝试在Windows Server 2012上进行编译. 参考CoreCLR的开发者指南(Developer ...
- [转]js动态获取图片长宽尺寸
http://blog.phpdr.net/js-get-image-size.html lightbox类效果为了让图片居中显示而使用预加载,需要等待完全加载完毕才能显示,体验不佳(如filick相 ...
- MyEclipse 8.5 优化实例
在用[MyEclipse] 写代码很容易卡死机,尤其是在对JSP文件的<%%>之间写代码的时候,只要一弹出智能提示就立刻卡死,程序失去响应,我以为是MyEclipse版本的问题,结果换了6 ...
- ASP.NET MVC请求处理管道生命周期的19个关键环节(13-19)
在上一篇"ASP.NET MVC请求处理管道生命周期的19个关键环节(7-12) ",体验了7-12关键环节,本篇继续. ⒀当请求到达UrlRoutingModule的时候,Url ...
- [译]面向初学者的Asp.Net状态管理技术
介绍 本文主要讲解Asp.Net应用程序中的状态管理技术(Asp.Net中有多种状态管理技术),并批判性地分析所有状态管理技术的优缺点. 背景 HTTP是无状态的协议.客户端发起一个请求,服务器响应完 ...