jdbc java例子_Spring JDBC 例子

要了解有关Spring JDBC框架与JdbcTemplate类的概念,让我们写这将实现所有在下面Student表的CRUD操作的简单例子。

CREATE TABLEStudent(ID INT NOT NULL AUTO_INCREMENT,NAME VARCHAR(20)NOT NULL,AGE INT NOT NULL,PRIMARY KEY(ID));

在开始之前,让我们使用Eclipse IDE,并按照下面的步骤来创建一个Spring应用程序:

步骤

描述

1

Create a project with a name SpringExample and create a package com.yiibai 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 andMainApp under the com.yiibai 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.

以下是数据访问对象接口文件StudentDAO.java的内容:

packagecom.yiibai;importjava.util.List;importjavax.sql.DataSource;publicinterfaceStudentDAO{/**

* This is the method to be used to initialize

* database resources ie. connection.

*/publicvoidsetDataSource(DataSourceds);/**

* This is the method to be used to create

* a record in the Student table.

*/publicvoidcreate(Stringname,Integerage);/**

* This is the method to be used to list down

* a record from the Student table corresponding

* to a passed student id.

*/publicStudentgetStudent(Integerid);/**

* This is the method to be used to list down

* all the records from the Student table.

*/publicListlistStudents();/**

* This is the method to be used to delete

* a record from the Student table corresponding

* to a passed student id.

*/publicvoiddelete(Integerid);/**

* This is the method to be used to update

* a record into the Student table.

*/publicvoidupdate(Integerid,Integerage);}

以下是Student.java文件的内容:

packagecom.yiibai;publicclassStudent{privateIntegerage;privateStringname;privateIntegerid;publicvoidsetAge(Integerage){this.age=age;}publicIntegergetAge(){returnage;}publicvoidsetName(Stringname){this.name=name;}publicStringgetName(){returnname;}publicvoidsetId(Integerid){this.id=id;}publicIntegergetId(){returnid;}}

以下是StudentMapper.java文件的内容:

packagecom.yiibai;importjava.sql.ResultSet;importjava.sql.SQLException;importorg.springframework.jdbc.core.RowMapper;publicclassStudentMapperimplementsRowMapper{publicStudentmapRow(ResultSetrs,introwNum)throwsSQLException{Studentstudent=newStudent();student.setId(rs.getInt("id"));student.setName(rs.getString("name"));student.setAge(rs.getInt("age"));returnstudent;}}

下面是实现类文件StudentJDBCTemplate.java 定义DAO接口StudentDAO:

packagecom.yiibai;importjava.util.List;importjavax.sql.DataSource;importorg.springframework.jdbc.core.JdbcTemplate;publicclassStudentJDBCTemplateimplementsStudentDAO{privateDataSourcedataSource;privateJdbcTemplatejdbcTemplateObject;publicvoidsetDataSource(DataSourcedataSource){this.dataSource=dataSource;this.jdbcTemplateObject=newJdbcTemplate(dataSource);}publicvoidcreate(Stringname,Integerage){StringSQL="insert into Student (name, age) values (?, ?)";jdbcTemplateObject.update(SQL,name,age);System.out.println("Created Record Name = "+name+" Age = "+age);return;}publicStudentgetStudent(Integerid){StringSQL="select * from Student where id = ?";Studentstudent=jdbcTemplateObject.queryForObject(SQL,newObject[]{id},newStudentMapper());returnstudent;}publicListlistStudents(){StringSQL="select * from Student";Liststudents=jdbcTemplateObject.query(SQL,newStudentMapper());returnstudents;}publicvoiddelete(Integerid){StringSQL="delete from Student where id = ?";jdbcTemplateObject.update(SQL,id);System.out.println("Deleted Record with ID = "+id);return;}publicvoidupdate(Integerid,Integerage){StringSQL="update Student set age = ? where id = ?";jdbcTemplateObject.update(SQL,age,id);System.out.println("Updated Record with ID = "+id);return;}}

以下是MainApp.java文件的内容:

packagecom.yiibai;importjava.util.List;importorg.springframework.context.ApplicationContext;importorg.springframework.context.support.ClassPathXmlApplicationContext;importcom.yiibai.StudentJDBCTemplate;publicclassMainApp{publicstaticvoidmain(String[]args){ApplicationContextcontext=newClassPathXmlApplicationContext("Beans.xml");StudentJDBCTemplatestudentJDBCTemplate=(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--------");Liststudents=studentJDBCTemplate.listStudents();for(Studentrecord: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 -----");Studentstudent=studentJDBCTemplate.getStudent(2);System.out.print("ID : "+student.getId());System.out.print(", Name : "+student.getName());System.out.println(", Age : "+student.getAge());}}

以下是配置文件beans.xml文件:

<?xml version="1.0"encoding="UTF-8"?>

http://www.springframework.org/schema/beans/spring-beans-3.0.xsd ">

创建源代码和bean配置文件完成后,让我们运行应用程序。如果一切顺利,这将打印以下信息:

------Records Creation--------

Created Record Name = Zara Age = 11

Created Record Name = Nuha Age = 2

Created Record Name = Ayan Age = 15

------Listing Multiple Records--------

ID : 1, Name : Zara, Age : 11

ID : 2, Name : Nuha, Age : 2

ID : 3, Name : Ayan, Age : 15

----Updating Record with ID = 2 -----

Updated Record with ID = 2

----Listing Record with ID = 2 -----

ID : 2, Name : Nuha, Age : 20

你可以尝试删除操作,我在例子中没有使用过,但现在你有一个工作的应用程序基于Spring的JDBC框架,它可以扩展到根据项目要求增加复杂的功能。还有其他的方法来访问,将使用针对NamedParameterJdbcTemplate和SimpleJdbcTemplate类的数据库,所以如果你有兴趣学习这些课程,请参考Spring框架手册。

¥ 我要打赏

纠错/补充

收藏

加QQ群啦,易百教程官方技术学习群

注意:建议每个人选自己的技术方向加群,同一个QQ最多限加 3 个群。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值