当前位置: 移动技术网 > IT编程>开发语言>Java > 在Java的Spring框架的程序中使用JDBC API操作数据库

在Java的Spring框架的程序中使用JDBC API操作数据库

2019年07月22日  | 移动技术网IT编程  | 我要评论

同时与数据库使用普通的旧jdbc的工作,它变得繁琐写不必要的代码来处理异常,打开和关闭数据库连接等,但spring的jdbc框架需要的所有低层次细节从打开连接,准备和执行sql语句,过程异常,处理事务,最后关闭连接。

所以,你所要做的只是定义连接参数,并指定要执行的sql语句,并做必要的工作,在每次迭代时从数据库中获取数据。

spring jdbc提供了一些方法和相应不同的类与数据库进行交互。我要采取经典和最流行的做法,利用jdbctemplateclass框架。这是管理的所有数据库的通信和异常处理中心框架类。

jdbctemplate 类
jdbctemplate类执行sql查询,更新语句和存储过程调用,在结果集和提取返回参数值进行迭代。它还捕捉jdbc的异常并将其转换为通用的,信息更丰富,除了在org.springframework.dao包中定义的层次结构。

jdbctemplate类的实例是一次配置的线程。所以,你可以配置一个jdbctemplate的一个实例,然后安全地注入这种共享引用到多个dao。

使用jdbctemplate类时,通常的做法是配置一个datasource在spring配置文件,然后依赖关系注入该共享数据源豆到dao类,jdbctemplate或者是在setter数据源创建。

配置数据源
让我们一起创造数据库test数据库表的 student 。假设使用mysql数据库,如果使用其他数据库,那么可以相应地改变你的ddl和sql查询。

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

现在,我们需要提供一个数据源给jdbctemplate类,因此它可以自行配置,以获得数据库访问。您可以配置数据源的xml文件中有一段代码,如下图所示:

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

数据访问对象 (dao)
dao表示这是通常用于数据库交互的数据访问对象。 dao的存在是为了提供读取和写入数据到数据库中,他们应该通过该应用程序的其余部分将访问它们的接口公开此功能的一种手段。

在spring的数据访问对象(dao)的支持使得它很容易与如jdbc,hibernate,jpa和jdo以一致的方式进行数据访问技术。

执行sql语句
让我们来看看如何使用sql和的jdbctemplate对象数据库中的表执行crud(创建,读取,更新和删除)操作。

查询一个整数:

string sql = "select count(*) from student";
int rowcount = jdbctemplateobject.queryforint( sql );

查询长整数:

string sql = "select count(*) from student";
long rowcount = jdbctemplateobject.queryforlong( sql );

使用绑定变量的简单查询:

string sql = "select age from student where id = ?";
int age = jdbctemplateobject.queryforint(sql, new object[]{10});

在查询字符串:

string sql = "select name from student where id = ?";
string name = jdbctemplateobject.queryforobject(sql, new object[]{10}, string.class);

查询并返回一个对象:

string sql = "select * from student where id = ?";
student student = jdbctemplateobject.queryforobject(sql, 
         new object[]{10}, new studentmapper());

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

查询并返回多个对象:

string sql = "select * from student";
list<student> students = jdbctemplateobject.query(sql,
             new studentmapper());

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

插入一行到表:

string sql = "insert into student (name, age) values (?, ?)";
jdbctemplateobject.update( sql, new object[]{"zara", 11} );

更新一行到表:
string sql = "update student set name = ? where id = ?";
jdbctemplateobject.update( sql, new object[]{"zara", 10} );

从表中删除行:

string sql = "delete student where id = ?";
jdbctemplateobject.update( sql, new object[]{20} );

执行ddl语句
您可以使用execute(...)方法的jdbctemplate来执行任何sql语句或ddl语句。下面是一个示例使用create语句创建一个表:

string sql = "create table student( " +
  "id  int not null auto_increment, " +
  "name varchar(20) not null, " +
  "age int not null, " +
  "primary key (id));"

jdbctemplateobject.execute( sql );

sql存储过程
simplejdbccall的类可以用来调用带有in和out参数的存储过程。你可以使用这种方法,而与任何喜欢的apache derby,db2,mysql和微软sql服务器,oracle和sybase rdbms中的工作。

其次,考虑以下的mysql存储过程这需要学生证和用out参数对应的学生的姓名和年龄的回报。因此,让我们使用mysql命令提示符下在测试数据库中创建该存储过程:

delimiter $$

drop procedure if exists `test`.`getrecord` $$
create procedure `test`.`getrecord` (
in in_id integer,
out out_name varchar(20),
out out_age integer)
begin
  select name, age
  into out_name, out_age
  from student where id = in_id;
end $$

delimiter ;

现在让我们写了spring jdbc应用程序,将执行我们的学生桌简单的创建和读取操作。
来创建一个spring应用程序:
以下是数据访问对象接口文件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 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();

}

以下是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:

package com.yiibai;

import java.util.map;

import javax.sql.datasource;
import org.springframework.jdbc.core.jdbctemplate;
import org.springframework.jdbc.core.namedparam.mapsqlparametersource;
import org.springframework.jdbc.core.namedparam.sqlparametersource;
import org.springframework.jdbc.core.simple.simplejdbccall;

public class studentjdbctemplate implements studentdao {
  private datasource datasource;
  private simplejdbccall jdbccall;

  public void setdatasource(datasource datasource) {
   this.datasource = datasource;
   this.jdbccall = new simplejdbccall(datasource).
            withprocedurename("getrecord");
  }

  public void create(string name, integer age) {
   jdbctemplate jdbctemplateobject = new jdbctemplate(datasource);
   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) {
   sqlparametersource in = new mapsqlparametersource().
               addvalue("in_id", id);
   map<string, object> out = jdbccall.execute(in);

   student student = new student();
   student.setid(id);
   student.setname((string) out.get("out_name"));
   student.setage((integer) out.get("out_age"));

   return student;
  }

  public list<student> liststudents() {
   string sql = "select * from student";
   
   list <student> students = jdbctemplateobject.query(sql, 
                   new studentmapper());
   return students;
  }

}

关于上面的程序几句话:你写的调用的执行代码时,需要创建包含in参数的一个sqlparametersource。重要的是要配合提供与存储过程中声明的参数名的输入值的名称。 execute方法接收传入的参数,并返回包含任何列在存储过程中指定的名称键入参数的映射。现在让我们修改主应用程序文件mainapp.java,这是如下:

package com.yiibai;
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("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("----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.yiibai.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
----listing record with id = 2 -----
id : 2, name : nuha, age : 2

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网