Spring基础 专题
专题目录
您的位置:java > Spring基础专题 > Spring JDBC 示例
Spring JDBC 示例
作者:--    发布时间:2019-11-20

想要理解带有 jdbc 模板类的 spring jdbc 框架的相关概念,让我们编写一个简单的示例,来实现下述 student 表的所有 crud 操作。

create table student(
   id   int not null auto_increment,
   name varchar(20) not null,
   age  int not null,
   primary key (id)
);

在继续之前,让我们适当地使用 eclipse ide 并按照如下所示的步骤创建一个 spring 应用程序:

步骤 描述
1 创建一个名为 springexample 的项目,并在创建的项目中的 src 文件夹下创建包 com.tutorialspoint
2 使用 add external jars 选项添加必需的 spring 库,解释见 spring hello world example 章节。
3 在项目中添加 spring jdbc 指定的最新的库 mysql-connector-java.jarorg.springframework.jdbc.jarorg.springframework.transaction.jar。如果这些库不存在,你可以下载它们。
4 创建 dao 接口 studentdao 并列出所有必需的方法。尽管这一步不是必需的而且你可以直接编写 studentjdbctemplate 类,但是作为一个好的实践,我们最好还是做这一步。
5 com.tutorialspoint 包下创建其他的必需的 java 类 studentstudentmapperstudentjdbctemplatemainapp
6 确保你已经在 test 数据库中创建了 student 表。并确保你的 mysql 服务器运行正常,且你可以使用给出的用户名和密码读/写访问数据库。
7 src 文件夹下创建 beans 配置文件 beans.xml
8 最后一步是创建所有的 java 文件和 bean 配置文件的内容并按照如下所示的方法运行应用程序。

以下是数据访问对象接口文件 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);
}

下面是 student.java 文件的内容:

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;
   }
}

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

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;
   }
}

下面是为定义的 dao 接口 studentdao 的实现类文件 studentjdbctemplate.java

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;
   }
}

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

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());      
   }
}

下述是配置文件 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>

当你完成创建源和 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 框架的工作应用程序,你可以根据你的项目需求来扩展这个框架,添加复杂的功能。还有其他方法来访问你使用 namedparameterjdbctemplatesimplejdbctemplate 类的数据库,所以如果你有兴趣学习这些类的话,那么你可以查看 spring 框架的参考手册。

网站声明:
本站部分内容来自网络,如您发现本站内容
侵害到您的利益,请联系本站管理员处理。
联系站长
373515719@qq.com
关于本站:
编程参考手册