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 ...
随机推荐
- 集合与Iterator
Iterator模式 是遍历集合类的标准访问方法.为的是不暴露类的内部结构,将访问逻辑从集合类中抽象出来. 想循环遍历数组,链表等结构数据,客户端都必须事先知道集合的内部结构,访问代码和集合本身是紧耦 ...
- android system.img
哥们要我做些模拟包,给过来的是mtk的底包,需要从system.img中提取部分文件. 网上一找资料,说是yaffs2文件系统,同时以前做linux的时候也是用yaffs2,感觉碰到老朋友了,不管三七 ...
- imageNamed、imageWithContentsOfFile、imageWithData
[UIImage imageNamed:ImageName]; 1.加载图片占据的内存较大 2.相同的图片只会加载一份到内存中,如果同时使用,使用同一个对象即可 3.当对象销毁,图片对象不会随着一起销 ...
- css3动画属性(transitions:property duration timing transition-delay)
transitions:property duration timing-function; transitionst他有三个参数:1) property:属性设置,例如background,colo ...
- android中 EditTex t的 inputType 属性
//文本类型,多为大写.小写和数字符号 android:inputType="none" android:inputType="text" a ...
- 斯坦福第三课:线性代数回顾(Linear Algebra Review)
3.1 矩阵和向量 3.2 加法和标量乘法 3.3 矩阵向量乘法 3.4 矩阵乘法 3.5 矩阵乘法的性质 3.6 逆.转置 3.1 矩阵和向量 如图:这个是 4×2 矩阵,即 4 行 ...
- 新机自动创建yum库
#!/bin/bash#for a newsystem to setup auto reposity YUM_DIR=/etc/yum.repos.dMOUNT_DIR=/mntDEV_DIR=&qu ...
- Mono for android真难用
最近要写个Android小项目,真的很少,几个按钮发送tcp或udp而已. 作为.net程序员当前是c#当先,Mono for android真是好,直接用c#一切都是那么熟悉,但发布时问题来了,需几 ...
- 跟我一起学WCF(7)——WCF数据契约与序列化详解
一.引言 在前面博文介绍到,WCF的契约包括操作契约.数据契约.消息契约和错误契约,前面一篇博文已经结束了操作契约的介绍,接下来自然就是介绍数据契约了.所以本文要分享的内容就是数据契约. 二.数据契约 ...
- 基于阿里云容器服务用docker容器运行ASP.NET 5示例程序
小试阿里云容器服务 之后,接下来有一个挡不住的小试冲动--用docker容器运行程序.首先想到的程序是 ASP.NET 5示例程序,于是参考msdn博客中的这篇博文 Running ASP.NET 5 ...